Leetcode: Reverse Nodes in k-Group

仅允许使用常数时间, 交换 k-group 的节点

 

思路:

1. 完全逆转一个链表: 每遍历到一个节点, 就将该节点放在链表首位

2. 在(1) 的基础上添加大小为 j 的窗口

 

总结:

1. 看来上一道题目思路也不是最优的

代码: update

 

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode *newHead = new ListNode(0);
        newHead->next = head;

        int cnt = 0;
        ListNode *cur_node = head;
        ListNode *last_tail = newHead;
        while(cur_node) {
            cnt++;
            if(cnt == k) {
                ListNode *cp = cur_node->next;

                cur_node->next = NULL;
                last_tail = reverseList(last_tail->next, last_tail);
                last_tail->next = cp;
                
                cur_node = cp;
                cnt = 0;
                continue;
            }
            cur_node = cur_node->next;
        }
        return newHead->next;
    }

    ListNode *reverseList(ListNode*head, ListNode*last_tail) {
        ListNode *next_node = head->next;
        ListNode *res = head;
        while(next_node) {
            ListNode *tmp = next_node->next;
            next_node->next = head;
            head = next_node;
            next_node = tmp;
        }
        last_tail->next = head;
        return res;
    }
};

 

 

 

posted @ 2013-12-05 16:00  SangS  阅读(1878)  评论(0编辑  收藏  举报