zoukankan      html  css  js  c++  java
  • LeetCode: Reverse Nodes in k-Group

    Title :

    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个元素翻转。翻转也很简单,让每个后添加的作为头就行了。如果到头,就需要将后面的全部加到链表尾部,同时记住,这个地方要return,因为已经结束,不然无法跳出循环。

    
    
    
    
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            // 向后查找k个元素,判断是否要进行翻转
            if (head == NULL) return NULL;
            ListNode *t = head;
            for (int i = 0; i < k - 1; i++) {
                t = t -> next;
                if (t == NULL) return head;
            }
            
            // 否则就利用递归,先将之后的部分进行翻转
            t = reverseKGroup(t -> next, k);
            
            // 然后再将前面这一部分翻转过来
            ListNode *s;
            while (k --) {
                // 这部分反转的代码需要仔细注意
                s = head; 
                head = head -> next;
                s -> next = t;
                t = s;
            }
            
            // 返回新的序列
            return t;
        }
    };
    

      

    Reverse Linked List II 

    Reverse a linked list from position m to n. Do it in-place and in one-pass.

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.

    思路:越简洁的代码越不容易出错。注意m=1的情况,q 指向m元素的前一个,p指向m元素

    class Solution{
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            ListNode* p = head,*q = NULL;
            int gap = n-m;
            while (--m > 0){
                q = p;
                p = p->next;
            }
            ListNode* tail,*end;
            tail = end = p;
            p = p->next;
            while(gap--){
                ListNode* t = p->next;
                p->next = tail;
                tail = p;
                p = t;
            }
            end->next = p;
            if (q == NULL)
                return tail;
            else
                q->next = tail;
            return head;
        }
    };
  • 相关阅读:
    妇女节 or 女人节 ?
    闲话电子商店(eshop)的设计和经营 (1)
    网站发展的若干思考
    历史上的今天
    升级到.net2.0失败
    冰峰战术
    【Struts2复习知识点十三】模块包含——配置struts.xml
    【Struts2复习知识点十二】web元素request session application等
    【Hibernate3.3】 slf4j 说明。
    【Struts2复习知识点二十四】 拦截器
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4428753.html
Copyright © 2011-2022 走看看