Chinaunix首页 | 论坛 | 博客
  • 博客访问: 117333
  • 博文数量: 53
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-24 16:22
文章存档

2014年(53)

我的朋友

分类: C/C++

2014-10-07 15:26:48

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.


Have you been asked this question in an interview?

这题之所以通过率不高是因为大家不知道怎么理解题意,其实就是反转k%n步就行了


  1. ListNode *rotateRight(ListNode *head, int k) {
  2.     if(head==NULL)
  3.         return NULL;
  4.     int length=0;
  5.     for(ListNode *p=head;p!=NULL;p=p->next)
  6.         length++;
  7.     k=k%length;
  8.     if(k==0)
  9.         return head;
  10.     ListNode *p0=head;
  11.     ListNode *p1=head;
  12.     int i=0;
  13.     for(;i<k && p1!=NULL;i++){
  14.         p1=p1->next;
  15.     }
  16.     while(p1->next!=NULL){
  17.         p0=p0->next;
  18.         p1=p1->next;
  19.     }
  20.     ListNode *tmp=p0->next;
  21.     p1->next=head;
  22.     p0->next=NULL;
  23.     return tmp;
  24. }

阅读(813) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~