LeetCode--Reverse Linked List II

来源:互联网 发布:php 打印数组的函数 编辑:程序博客网 时间:2024/06/05 20:36

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.

思路:头插法。这是一个翻转链表题目的扩展,在头插法的基础上考虑在一个区间内反转。那么,首先要找到prev指针,然后确定3个指针head2,prev,cur的位置,头插法把cur指针内容插到head2后面,然后更新cur指针。

/** * 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 dummy(0);        dummy.next=head;        ListNode *prev=&dummy;        for(int i=0;i<m-1;i++){            prev=prev->next;        }        ListNode *head2=prev;        prev=head2->next;        ListNode *cur=prev->next;        for(int i=m;i<n;i++){            prev->next=cur->next;            cur->next=head2->next;            head2->next=cur;            cur=prev->next;        }        return dummy.next;    }};
原创粉丝点击