首页 > 其他 > 详细

leetcode 25: Reverse Nodes in k-Group

时间:2015-12-21 18:10:30      阅读:158      评论:0      收藏:0      [点我收藏+]

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.You may not alter the values in the nodes, only nodes itself may be changed.Only constant memory is allowed.

For example,Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

这个题目的复杂在单链表但是需要回溯,我做的很简单,就是每K个作为一个循环,在循环内反转链表的val,思路简单,只对链表的value进行修改反转。

代码:

 1 ListNode* reverseKGroup(ListNode* head, int k)
 2 {
 3     if (k<=1)
 4     {
 5         return head;
 6     }
 7     if (head==NULL)
 8     {
 9         return head;
10     }
11     if (head->next==NULL)
12     {
13         return head;
14     }
15     ListNode* p=head;
16     ListNode* q=head;
17     ListNode* m=head;
18     while(p->next!=NULL)
19     {
20         q=p;
21         for(int i=0;i<k-1;i++)
22         {
23             if (p->next!=NULL)
24             {
25                 p=p->next;
26             }
27             else
28                 return head;
29         }
30         m=p;
31         for(int j=0;j<k/2;j++)
32         {
33             int temp=m->val;
34             m->val=q->val;
35             q->val=temp;
36             q=q->next;
37 
38             m=q;
39             for(int i=0;i<k-2*j-3;i++)
40                 m=m->next;
41         }
42         if (p->next!=NULL)
43         {
44             p=p->next;
45         }
46         else
47             return head;
48     }
49     return head;
50 }

 

leetcode 25: Reverse Nodes in k-Group

原文:http://www.cnblogs.com/zhang-hill/p/5063921.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!