首页 > 其他 > 详细

Leetcode Reverse Nodes in k-Group

时间:2014-07-03 23:51:16      阅读:545      评论: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个节点就反转一次即可

class Solution {
public:
    ListNode *reverse(ListNode* head, ListNode* tail){
        ListNode *newHead = NULL,*p = head;
        while(p!=tail){
            ListNode* tmp = p->next;
            p->next = newHead;
            newHead = p;
            p = tmp;
        }
        return newHead;
    }
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode* newHead = new ListNode(0),*newPre = newHead;
        newHead->next = head;
        ListNode* p = head,*pre = head;
        int cnt = 0;
        while(p){
            cnt++;
            ListNode *tmp = p->next;
            if(cnt == k){
                newPre->next = reverse(pre,p->next);
                newPre = pre;
                pre = tmp;
                cnt = 0;
            }
            p = tmp;
        }
        newPre->next = pre;
        return newHead->next;
    }
};

 

Leetcode Reverse Nodes in k-Group,布布扣,bubuko.com

Leetcode Reverse Nodes in k-Group

原文:http://www.cnblogs.com/xiongqiangcs/p/3823275.html

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