标签:
/**
* ID: 61
* Name: Rotate List
* Data Structure: Linked List
* Time Complexity:
* Space Complexity:
* Tag: LinkList
* Difficult: Medium
* Problem:
* Given a list, rotate the list to the right by k places, where k is non-negative.
* Given 1->2->3->4->5->NULL and k = 2
* return 4->5->1->2->3->NULL.
* Solution:
* The idea of solution is very similar to the the rotate array.
* use a new reverse function and reverse the (0,n-k),(n-k,n), then combine them and reverse all the link.
* =======================>>>>> Another Easy solution:
* Because this is the Link, so we can connect the tail to the head. So we can directly focus on which is the
* result head for the new link, then we split it from the beginning.
* What to learn:
* For the link, we should consider the circle that we can use for our purpuse.
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
**/
要注意到的:
1. 链表要先判断其head是不是为NULL
2. 链表如果其整体顺序不变的话,记得头尾相结合后可以有很好的效果。
本题解法:
第一: 和 Rotate Array 的算法是一样的, 先分成两部分,反转前 n-k,后k, 然后合并,旋转整体。
第二: 因为是 Linklist,所以可以先找到新link的head,然后把新的 head 和head前面的next元素设置一下。
第一种
1 class Solution { 2 public: 3 ListNode *rotateRight(ListNode *head, int k) { 4 if(head == NULL || head->next == NULL) 5 return head; 6 int length = 0; 7 ListNode *p = head; 8 while(p) 9 { 10 length++; 11 p = p -> next; 12 } 13 k = k%length; 14 if (k==0) 15 return head; 16 int cnt = length - k -1; 17 ListNode *first, *second; 18 first = p = head; 19 while(cnt) 20 { 21 cnt --; 22 p = p->next; 23 } 24 second = p->next; 25 p -> next = NULL; 26 first = reverseList(first); 27 second = reverseList(second); 28 p = first; 29 while(p->next) 30 { 31 p = p->next; 32 } 33 p -> next = second; 34 head = reverseList(first); 35 return head; 36 } 37 ListNode *reverseList(ListNode *head) 38 { 39 ListNode * fakeNode = new ListNode(0); 40 ListNode *cur, *pre; 41 fakeNode -> next = cur = head; 42 pre = fakeNode; 43 44 while(cur) 45 { 46 ListNode *temp = cur; // choose a tempary variable and store the current pointer 47 cur = cur -> next; 48 temp -> next = pre; // change the current pointer to point the former one. 49 pre = temp; 50 } 51 delete cur; 52 delete fakeNode; 53 head ->next = NULL; 54 return pre; 55 } 56 };
第二种:
// A new and better solution! class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head == NULL || head->next == NULL) return head; ListNode * p = head; int length = 1; while(p->next) { length ++; p = p->next; } if(k==0) return head; p->next = head; k = k%length; int cnt = length - k -1; p = head; while(cnt) { cnt --; p = p->next; } head = p -> next; p -> next = NULL ; return head; } };
标签:
原文地址:http://www.cnblogs.com/zhuguanyu33/p/4418948.html