标签:
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
.
解题思路:一开始想到比较简单的方法是用哈希,建立一个索引与结点的map,然后根据要求调整位置就可以了.另外一种解法可以用双指针,用快慢指针找到需要移位的结点即可.
#include<iostream> #include<vector> using namespace std; //Definition for singly - linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *rotateRight(ListNode *head, int k) { if (head == NULL) return NULL; ListNode*FirstNode = head; ListNode*LastNode = head; for (int i = 0; i != k;++i){ LastNode = LastNode->next; if (LastNode == NULL) LastNode =head; } for (; LastNode->next != NULL;LastNode=LastNode->next,FirstNode =FirstNode->next){} LastNode->next = head; ListNode* ResultNode = FirstNode->next; //最终链表的头结点. FirstNode->next = NULL; return ResultNode; }
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/43409493