61. Rotate List(旋转链表)

本文介绍了一种链表旋转算法,通过两种方法实现链表的右旋。第一种方法通过多次调用一次旋转函数来完成旋转,但效率较低;第二种方法通过将链表闭合成环,再断开新尾节点和新头节点前的连接,实现了更高效的链表旋转。

题目描述

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

方法思路

Approach1:

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        //Runtime: 8054 ms, faster than 5.01%
        //Memory Usage: 38.7 MB
       if(head == null || head.next == null)
           return head;
        while(k > 0){
        head = rotateOnceTime(head);
            k--;
        }
        return head;
    }
    public ListNode rotateOnceTime(ListNode head){
       // ListNode con = head;
        ListNode cur = head;
        while(cur.next.next != null)
            cur = cur.next;
        // 循环结束后,cur 为尾部倒数第二个结点
        ListNode tail = cur.next;
        cur.next = cur.next.next;//令cur成为尾结点
        tail.next = head;//tail结点成为头结点
        return tail;
    }
}

Approach2:

The nodes in the list are already linked, and hence the rotation basically means

To close the linked list into the ring.

To break the ring after the new tail and just in front of the new head.
class Solution {
    //Runtime: 6 ms, faster than 100.00%
    //Memory Usage: 38.1 MB, less than 20.71%
  public ListNode rotateRight(ListNode head, int k) {
    // base cases
    if (head == null) return null;
    if (head.next == null) return head;

    // close the linked list into the ring
    ListNode old_tail = head;
    int n;
    for(n = 1; old_tail.next != null; n++)
      old_tail = old_tail.next;
    old_tail.next = head;//step1、2
    // n 为链表的长度
    // find new tail : (n - k % n - 1)th node;实际上是(n - k % n)th node
    // and new head : (n - k % n)th node;实际上是(n - k % n + 1)th node
    ListNode new_tail = head;
    for (int i = 0; i < n - k % n - 1; i++)
      new_tail = new_tail.next;
    ListNode new_head = new_tail.next;

    // break the ring
    new_tail.next = null;//step3、4

    return new_head;
  }
}

Complexity Analysis

Time complexity : O(N)  where Nis a number of elements in the list.

Space complexity : O(1) since it's a constant space solution.
#include <stdio.h> #include <stdlib.h> // 定义链表节点结构 typedef struct ListNode { int val; struct ListNode *next; } ListNode; // 创建新节点 ListNode* createNode(int val) { ListNode* newNode = (ListNode*)malloc(sizeof(ListNode)); newNode->val = val; newNode->next = NULL; return newNode; } // 构建链表 ListNode* buildList(int arr[], int n) { if (n == 0) return NULL; ListNode* head = createNode(arr[0]); ListNode* cur = head; for (int i = 1; i < n; i++) { cur->next = createNode(arr[i]); cur = cur->next; } return head; } // 打印链表 void printList(ListNode* head) { ListNode* cur = head; while (cur) { printf("%d ", cur->val); cur = cur->next; } printf("\n"); } // 旋转链表函数 ListNode* rotateRight(ListNode* head, int k) { if (k == 0 || head == NULL || head->next == NULL) return head; int n = 1; struct ListNode* tail = head; while (tail->next != NULL) { tail = tail->next; n++; } int movenum = k % n; if (movenum == 0) return head; tail->next = head; int addnum = n - movenum; while (addnum--) tail = tail->next; struct ListNode* newhead = tail->next; tail->next = NULL; return newhead; } int main() { // 测试用例:head = [1,2,3,4,5], k = 2 int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; ListNode* head = buildList(arr, n); printf("原始链表:"); printList(head); ListNode* rotatedHead = rotateRight(head, k); printf("旋转后的链表:"); printList(rotatedHead); // 释放内存 ListNode* cur = rotatedHead; while (cur) { ListNode* temp = cur; cur = cur->next; free(temp); } return 0; }简化代码
最新发布
09-26
以下是一个简化的C语言实现旋转链表的代码,包含链表节点创建、构建、打印和旋转功能: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct Node { int data; struct Node* next; } Node; // 创建新节点 Node* createNode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; return newNode; } // 构建链表 Node* buildList(int arr[], int n) { if (n == 0) return NULL; Node* head = createNode(arr[0]); Node* current = head; for (int i = 1; i < n; i++) { current->next = createNode(arr[i]); current = current->next; } return head; } // 打印链表 void printList(Node* head) { Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); } // 旋转链表 Node* rotateList(Node* head, int k) { if (head == NULL || head->next == NULL || k == 0) return head; int len = 1; Node* tail = head; while (tail->next != NULL) { tail = tail->next; len++; } k = k % len; if (k == 0) return head; Node* newTail = head; for (int i = 0; i < len - k - 1; i++) { newTail = newTail->next; } Node* newHead = newTail->next; newTail->next = NULL; tail->next = head; return newHead; } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; Node* head = buildList(arr, n); printf("原始链表: "); printList(head); head = rotateList(head, k); printf("旋转后的链表: "); printList(head); return 0; } ``` ### 代码说明: 1. **创建节点**:`createNode` 函数用于创建一个新的链表节点,分配内存并初始化节点的数据和指针。 2. **构建链表**:`buildList` 函数根据给定的数组构建链表,依次创建节点并连接起来。 3. **打印链表**:`printList` 函数遍历链表并打印每个节点的数据。 4. **旋转链表**:`rotateList` 函数实现链表旋转,首先计算链表的长度,然后找到新的头节点和尾节点,最后重新连接链表。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值