• 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.

    用了栈。注意指针移动时不同指针的分工。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *reverseBetween(ListNode *head, int m, int n) {
            ListNode *guard = new ListNode(0);
            guard -> next =head;
            ListNode *pre = guard;
            ListNode *temp = head;
    
            ListNode *re ;
            stack<ListNode*> sk;
            
            
            for(int i =1 ; i < m ;i++)
            {
                pre = pre->next;
                temp = pre ->next;
            }
            ListNode *tail = temp;
            temp =temp->next;
            for(int i = m ; i < n ; i++)
            {
                sk.push(temp);
                temp =temp->next;
            }
            while(!sk.empty())
            {
                ListNode* tt =sk.top();
                pre->next = tt;
                pre =pre->next;
                sk.pop();
            }
            pre->next = tail;
            tail->next =temp;
            return guard->next;
        }
    };
    

      

  • 相关阅读:
    Linux 常用命令总结(二)
    Linux(CentOS7)使用 RPM 安装 mysql 8.0.11
    Linux(CentOS7) 相关软件安装
    8、js——字符串
    7、js——数组
    6、js——创建对象方式
    5、js——this说明
    4、js——函数
    4、js——对象
    2、js编写位置
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3605189.html
Copyright © 2020-2023  润新知