码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Reverse Nodes in k-Group

时间:2015-04-15 16:32:57      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

Title :

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步,如果这k步没有到头,要将中间的k个元素翻转。翻转也很简单,让每个后添加的作为头就行了。如果到头,就需要将后面的全部加到链表尾部,同时记住,这个地方要return,因为已经结束,不然无法跳出循环。


ListNode *reverseKGroup(ListNode *head, int k) { ListNode * h = new ListNode(0); ListNode * p_cur = h; ListNode * p = head,*cur = head; while (p != NULL){ int count = 0; while (cur != NULL && count < k){ cur = cur->next; count += 1; } if (count == k){ count = 0; ListNode *tail = NULL; ListNode * p_cur_tmp = p; while (count++ < k){ ListNode* tmp = p->next; p->next = tail; tail = p; p = tmp; } p_cur->next = tail; p_cur = p_cur_tmp; } else{ p_cur->next = p; return h->next; } } return h->next; }

 

LeetCode: Reverse Nodes in k-Group

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4428753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!