旋转链表

要求

给定一个链表1->2->3->4->5->NULL和一个k=2,返回4->5->1->2->3->NULL

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
using namespace std;
struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    int length(ListNode* head){
        int count = 0;
        ListNode* p = head;
        while (p!=NULL) {
            count++;
            p = p->next;
        }
        return count;
    }
    ListNode* rotateRight(ListNode* head, int k) {
        if (head==NULL||head->next==NULL) {
            return head;
        }else if(k==0){
            return head;
        }else{
            int n = length(head);
            //如果k大于链表长度则取余
            k = k%n;
            if (k==0) {
                return head;
            }

            //关键步骤
            ListNode* p = head;
            for (int i =0; i<n-k-1; i++) {
                p = p->next;
            }

            //取得新链表的头和尾
            ListNode* newEnd = p;
            ListNode* newHead = p->next;

            while (p->next!=NULL) {
                p = p->next;
            }
            ListNode* touch = p;
            touch->next = head;
            newEnd->next = NULL;
            return newHead;
        }
    }
};
int main(int argc, const char * argv[]) {

    return 0;
}

Comments