LeetCode 25. Reverse Nodes in k-Group

来源:互联网 发布:oracle导出数据库命令 编辑:程序博客网 时间:2024/06/05 13:00

25. Reverse Nodes in k-Group

原题如下:

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked 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是一个正数,且小于等于链表长度,所以不需要考虑k大于链表和小于0的情况。

解题思路如下:
 1. 循环链表;
 2. 每次循环链表时,使用计数器count,并将当前节点复制到一条中间链表中;
 3. 当count的值等于k时,将中间链表进行翻转,并将翻转后的链表拼接到结果链表中,同时重置中间链表;
 4. 结束循环后,如果中间链表的next节点不为空,说明最后剩余不足k个节点,将中间链表直接拼接到结果链表中;
 5. 返回结果链表。

具体代码实现如下:
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverse_linked_list(ListNode* head) {        stack<int> m_stack;        ListNode* first = head;        while(first) {            m_stack.push(first->val);            first = first->next;        }        first = new ListNode(0);        ListNode* tmp_first = first;        while(!m_stack.empty()) {            first->next = new ListNode(m_stack.top());            m_stack.pop();            first = first->next;        }        return tmp_first->next;    }        ListNode* reverseKGroup(ListNode* head, int k) {        if (k <= 1)            return head;        ListNode *result = new ListNode(0), *tmp_result = result, *first = head;        // tmp list stores k nodes temporarily        ListNode *tmp = new ListNode(0), *tmp_tmp = tmp;        int count = 0;        while(first) {            count++;            tmp->next = new ListNode(first->val);            tmp = tmp->next;            if (count == k) {                // reverse tmp list and store it in result list                result->next = reverse_linked_list(tmp_tmp->next);                // let result pointer point to the last node                while(result && result->next)                    result = result->next;                // restore tmp list                tmp = new ListNode(0), tmp_tmp = tmp;                count = 0;            }            first = first->next;        }        // when tmp list is not null, store it in result list        if (tmp_tmp->next) {            result->next = tmp_tmp->next;        }        return tmp_result->next;    }};


原创粉丝点击