要说这题没什么新鲜玩意,我确实第一次没提交过,不是什么大难题,考虑不周到,马虎之类,人生有多少时候我们是跌倒在这里呢?
// LeetCode_RotateList.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *rotateRight(ListNode *head, int k) {
if (head==NULL||k==0)
return head;
ListNode *q=head,*p=head;
ListNode *newhead = head;
int len = 0;
while(newhead!=NULL)
{
newhead=newhead->next;
len++;
}
if(k%len==0)
return head;
if(k>len)
k = k%len;
while(k>0&&q->next!=NULL)
{
q = q->next;
k--;
}
while(q->next!=NULL)
{
q = q->next;
p = p->next;
}
newhead = p->next;
p->next = NULL;
q->next = head;
return newhead;
}
int _tmain(int argc, _TCHAR* argv[])
{
ListNode *a = new ListNode(1);
ListNode *b = new ListNode(2);
ListNode *c = new ListNode(3);
ListNode *d = new ListNode(4);
ListNode *e = new ListNode(5);
a->next = b;
b->next = c;
c->next = d;
d->next = e;
ListNode *newhead = rotateRight(a,2);
ListNode *p = newhead;
while(p!=NULL)
{
cout<<p->val<<" ";
p = p->next;
}
system("pause");
return 0;
}