http://oj.leetcode.com/problems/rotate-list/
取得后面k个节点,然后截断插到前面。如果k比list长,则按照求余算。
去后面的k个节点:使用两个指针,第一个指针比第二个指针先走k步,然后两个一起往后走,等到第一个到达最后一个节点,第二个就是倒数第k个节点。
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *rotateRight(ListNode *head, int k) { //找到倒数第k个节点 ListNode *pEnd = head,*pLastK = head; int _k = k; if(k==0 ||head == NULL) return head; //计算共有多少个节点 ListNode *node_count = head; int count = 0; while(node_count) { node_count = node_count->next; count++; } if(_k>count) _k = k%count; if(_k == 0) return head; while(_k--) { if(pEnd == NULL) return head; pEnd = pEnd->next; } if(pEnd == NULL) return head; while(pEnd->next) { pEnd = pEnd->next; pLastK = pLastK->next; } //截断 ListNode *ans = pLastK->next; pLastK->next = NULL; //再插到前面 ListNode *temp = ans; while(temp->next) { temp = temp->next; } temp->next = head; return ans; } }; int main() { Solution myS; ListNode *n1 = new ListNode(1); ListNode *n2 = new ListNode(2); ListNode *n3 = new ListNode(3); ListNode *n4 = new ListNode(4); ListNode *n5 = new ListNode(5); n1->next = n2; n2->next = n3; n3->next = n4; n4->next = n5; myS.rotateRight(n4,4); return 0; }