现在的位置: 首页 > 综合 > 正文

Leetcode Reverse Nodes in k-Group

2019年03月10日 ⁄ 综合 ⁄ 共 933字 ⁄ 字号 评论关闭

题目:

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

解题:

暴力,注意边缘

代码:

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(k == 1 || head == NULL) return head;
        ListNode *preHead = new ListNode(-1);
        preHead->next = head;
        ListNode *pre = preHead, *now = head;
        while(1) {
            bool flag = 0;
            int i;
            ListNode *tmp = now;
            for(i = 0; i < k; i ++) {
                if(tmp == NULL) {
                    flag = 1;
                    break ;
                }
                tmp = tmp->next;
            }
            if(flag || i < k) break;
            tmp = now;
            now = now->next;
            ListNode *recNx = now->next;
            for(int i = 1; i < k; i ++, tmp = now, now = recNx, recNx = recNx->next) {
                now->next = tmp;
                if(recNx == NULL) {
                    tmp = now;
                    now = recNx;
                    break;
                }
            }
            ListNode *t = pre->next;
            pre->next->next = now;
            pre->next = tmp;
            pre = t;
        }
        return preHead->next;
    }
};

抱歉!评论已关闭.