Problem Description:
Reverse a linked list from position m toN. 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.
Basic ideas:
The idea is simple, flip the list of points to note the pointer can be.
Code:
Public ListNode Reverse (listnode head,int N) //java {listnode tmp = head;int Step = 1;tmp = Tmp.next; ListNode tmphead = head; ListNode p = null; ListNode pre = Head;while (Step < n) {p = Tmp.next;tmp.next = Head;head = Tmp;pre.next = P;//head.next = Null;tmp = P;st ep++;} Tmphead.next = P;return head; } Public ListNode Reversebetween (listnode head, int m, int n) { if (head = = NULL | | head.next = = NULL | | m==n) return Head; ListNode result = new ListNode (0); Result.next = head; ListNode p = head; ListNode pre =result; int pos = 1; while (pos! = m) { pre = P; p = p.next; pos++; } ListNode tmphead = reverse (P, n-m+1); Pre.next = Tmphead; return result.next; }
[Leetcode] Reverse Linked List II