25. Reverse Nodes in k-Group

来源:互联网 发布:互联网数据开发是什么 编辑:程序博客网 时间:2024/04/30 14:46

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个。

代码如下(28ms):

/** * 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) {        ListNode h(0);        h.next=head;        ListNode *pre=&h, *begin=&h, *end;        //pre表示遍历结点的前一个结点        //begin表示要逆置k个结点的前一个结点,end表示要逆置k个结点的后一个结点        stack<ListNode*> s;        while(pre->next){//不足k个进栈            if(k!=s.size()){                s.push(pre->next);                pre=pre->next;            }else{//有k个了就逆置                end=pre->next;//记录本次end                pre=begin;                while(!s.empty()){                    pre->next=s.top();                    s.pop();                    pre=pre->next;                }                begin=pre;//记录下次begin                pre->next=end;//连起来            }        }        return h.next;    }};



0 0
原创粉丝点击