Reverse Linked List
Reverse a singly linked list.
Note
Create tail = null;
Head loop through the list: Store head.next, head points to tail, tail becomes head, head goes to stored head.next;
Return tail.
Solution
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode tail = null;
while (head != null) {
ListNode temp = head.next;
head.next = tail;
tail = head;
head = temp;
}
return tail;
}
}
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.
Solution
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
int i = 0;
while (i++ < m-1) {//注意这里,pre只要走到第m-1位
pre = pre.next;
}
ListNode cur = pre.next;
ListNode next = pre.next.next;
for (i = 0; i < n-m; i++) {
cur.next = next.next;
next.next = pre.next;
pre.next = next;
next = cur.next;
}
return dummy.next;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。