61. 旋转链表
简单题。画图很容易能想明白。 要旋转,可以通过取模解决。
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
#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 )
{
if( head == NULL || head->next == NULL )
return head;
int length = 1;
ListNode* ptr = head;
while( ptr->next != NULL )
{
length++;
ptr = ptr->next;
}
ptr->next = head;
int step = length - k % length;
while( step > 0 )
{
ptr = ptr->next;
head = head->next;
step--;
}
ptr->next = NULL;
return head;
}
};
int main( int argc, char* argv[] )
{
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;
Solution s;
ListNode* ret = s.rotateRight( n1, 4 );
while( ret != NULL )
{
cout << ret->val;
ret = ret->next;
if( ret != NULL )
cout << "->";
}
cout << endl;
return 0;
}

浙公网安备 33010602011771号