- Reverse Linked List
Iterative:core Code
if NULL NULL ) return= null; while NULL ) { = current.next; = head; = current ; = Temp.next;} return head;
Recurring:core Code
Public ListNode reverselist (ListNode head) { if (head = = NULL | | head.next = = NULL) return head; ListNode second = Head.next; Head.next = null; ListNode res = reverselist (second); Second.next = head; return res; }
Reverse Linked List II
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.
Point:reverse
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {public ListNode Reversebetween (listnode head, int m, int n) { if (head = = NULL | | head.next = = NULL) retur n Head; ListNode res = new ListNode ( -1); Res.next = head; ListNode pre = res; for (int i = 0; i < m-1; i + +) { pre = Pre.next; } ListNode first = Pre.next; ListNode second = First.next; for (int i = 0; i < n-m; i++) { first.next = Second.next; Second.next = Pre.next; Pre.next = second; second = First.next; } return res.next; } }
ListNode Review Reverselistnode