Leetcode Reverse Linked List II

来源:互联网 发布:微商和淘宝的区别 编辑:程序博客网 时间:2024/05/02 05:03

题意:使得链表中的某一段倒序。

思路:简单模拟。

/** * 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) {        if(head == NULL) return head;                ListNode* myhead = new ListNode(0);        myhead->next = head;                ListNode* next = myhead;        ListNode* s = myhead;        ListNode* e = myhead;        ListNode* s1 = myhead;        int mym = m - 1;        int myn = n;        while(mym --) {            s = s->next;        }        while(m --) {            s1 = s1->next;        }                while(myn --) {            e = e ->next;        }        ListNode* temp = e->next;                reverseList(s1, e);        s->next = e;        s1->next = temp;//cout << "here";                return myhead->next;            }        void reverseList(ListNode* s, ListNode* e) {        stack<ListNode*> mys;        while(s != e) {            mys.push(s);            s = s->next;        }                while(!mys.empty()) {            ListNode* temp = mys.top();            mys.pop();            s->next = temp;            s = temp;        }        return;    }};


0 0