[LeetCode] Reverse Linked List II,leetcodelinked

來源:互聯網
上載者:User

[LeetCode] Reverse Linked List II,leetcodelinked

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->NULL, m = 2 and n = 4,

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

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

解題思路

解題思路與上一篇Reverse Linked List類似,只不過這裡是反轉部分鏈表。
因此,只需將m到n部分翻轉,然後將m的首碼beforeM指向該部分反轉後的頭結點即可。如果beforeM為NULL,則m=1,m到n部分的頭結點即為鏈表的頭結點。

實現代碼
//Runtime: 4 ms#include <iostream>#include <cstdlib>#include <cmath>using namespace std;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 *cur = head;        ListNode *beforeM = NULL;        for (int i = 1; i < m; i++)        {            beforeM = cur;            cur = cur->next;        }        ListNode *localhead = cur;        ListNode *pre = cur;        cur = cur->next;        int count = n - m;        while (count--)        {            pre->next = cur->next;            cur->next = localhead;            localhead = cur;            cur = pre->next;        }        if (beforeM == NULL)        {            head = localhead;        }        else        {            beforeM->next = localhead;        }        return head;    }};void printList(ListNode *head){    while(head != NULL)    {        cout<<head->val<<" ";        head = head->next;    }    cout<<endl;}void dropList(ListNode *head){    if (head == NULL) return;    ListNode *temp;    while (head != NULL)    {        temp = head->next;        delete head;        head = temp;    }}int main(){    ListNode *head = new ListNode(0);    ListNode *cur = head;    for (int i = 0; i < 10; i++)    {        ListNode *newnode = new ListNode(floor(rand()%77));        cur->next = newnode;        cur = newnode;    }    printList(head);    Solution s;    head = s.reverseBetween(head, 2, 5);    printList(head);    dropList(head);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.