题目链接:https://leetcode.com/problems/rotate-list/
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if(!head) return head; ListNode *pHead = new ListNode(0); pHead->next = head; int n = 0, i = 0; ListNode* p = pHead, *rear = NULL; while(p->next)//找出链表长度和尾结点 { n++; p = p->next; if(!p->next) rear = p; } p = pHead; while(i < n-k%n)//走n - k 步到要旋转的结点前 { p = p->next; i++; } if(p == pHead)//如果不需要旋转 { head = pHead->next; delete pHead; return head; } rear->next = pHead->next; pHead->next = p->next; p->next = NULL; head = pHead->next; delete pHead; return head; } };
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if(!head) return head; ListNode *p = head, *q; int n =1, i =0; while(p->next)//找出长度 { n++; p = p->next; } p->next = head; while(i < n-k%n)//找到断裂点 { p = p->next; i++; } head = p->next; p->next = NULL; return head; } };