Reverse Nodes in k-Group

来源:互联网 发布:linux如何查看内核日志 编辑:程序博客网 时间:2024/06/06 07:30

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

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseKGroup(ListNode* head, int k) {        if(!head || k <=1){            return head;        }        ListNode dummy(0);        dummy.next = head;        ListNode * front = &dummy;        ListNode * end = NULL;        while(front){            end = front;            for(int i = 0; i < k; i++){                end = end->next;                if(!end){                    return dummy.next;                }            }            front = reverse(front, end->next);        }        return dummy.next;    }    //对(front, end)左右开区间的链表元素进行逆序    ListNode * reverse(ListNode * front, ListNode * end){        ListNode * pre = front;        ListNode * cur = pre->next;        while(cur->next != end){            ListNode * suc = cur->next;            cur->next = suc->next;            suc->next = pre->next;            pre->next = suc;        }        //注意应该返回逆序后的最后一个节点作为下一个group的前驱节点        return cur;    }};
0 0