• 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;
        }
    };
  • 相关阅读:
    安装gmsll
    常用LInux命令和操作
    yum 一键安装 jdk
    Linux目录详解,软件应该安装到哪个目录
    安装npm
    linux安装mysql (rpm + yum)
    springboot 打包jar 运行找资源文件
    rpm包安装java jar开机自启
    centos7设置服务开机自启
    linux(centos7) nginx 配置
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4428753.html
Copyright © 2020-2023  润新知