Reverse Linked List II

来源:互联网 发布:商务部 融资租赁数据 编辑:程序博客网 时间:2024/06/06 00:48

描述
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->nullptr, m = 2 and n = 4,
return 1->4->3->2->5->nullptr.
Note: Given m, n satisfy the following condition: 1  m  n  length of list.
方法2. 找到m节点之后,保存m之前的一个节点pre,m后面的点插入到pre前面。

具体流程分为三个步骤,如下图所示:
这里写图片描述

/** * 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 || m==n) return head;        ListNode *hhead=new ListNode(-1);        hhead->next=head;        ListNode *pre=hhead;        int i;        for(i=1;i<m;i++){            pre=pre->next;        }        ListNode *mnode=pre->next;        for(i=m;i<n;i++){            ListNode *cur=mnode->next;            mnode->next=cur->next;            cur->next=pre->next;            pre->next=cur;        }        return hhead->next;    }};
0 0
原创粉丝点击