美文网首页
[leetcode -- LinkList]25. Revers

[leetcode -- LinkList]25. Revers

作者: jowishu | 来源:发表于2016-10-30 00:01 被阅读15次

    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.

    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

    分析: 基础题考察链表的基本操作. 首先遍历一遍链表, 记录链表的节点数; 然后求出分组数. 对每一分组分别进行处理, 在处理的过程中设置两个指针, 分别指向当前节点和当前节点的下一个节点, 采用头插法逆序每一分组的节点.

    code:

    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(!head)
                return NULL;
            if(k == 1)
                return head;
    
            int nums = 0;
            int groups = 0;
            ListNode* q = NULL, *r = NULL;
    
            for(q = head; q; q = q->next) {
                nums++;
            }
            groups = nums / k;
            r = head;
            ListNode* p = new ListNode(0);
            head = p;
            while(groups--) {
                for (int i = 0; i < k; ++i) {
                    q = r;
                    r = r->next;
                    q->next = p->next;
                    p->next = q;
                }
                for (int i = 0; i < k; ++i) {
                    p = p->next;
                }
            }
            p->next = r;
            q = head->next;
            delete head;
            return q;
        }
    };
    

    相关文章

      网友评论

          本文标题:[leetcode -- LinkList]25. Revers

          本文链接:https://www.haomeiwen.com/subject/hugyuttx.html