206. Reverse Linked List
Reverse a singly linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//iterative
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while(head != null){
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}
//recursive
class Solution {
public ListNode reverseList(ListNode head) {
return helper(head,null);
}
public ListNode helper(ListNode head,ListNode res){
if(head == null) return res;
ListNode next = head.next;
head.next = res;
return helper(next,head);
}
}
92. 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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//因为头结点不确定,所以使用dummpy Node
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null || m > n) return head;
ListNode dummpy = new ListNode(0);
dummpy.next = head;
head = dummpy;
//首先找到m的前一个点
for(int i = 1; i < m; i++){
if(head == null) return null;
head = head.next;
}
ListNode premNode = head;
ListNode mNode = head.next;
ListNode nNode = mNode,postnNode = mNode.next;
// reverse指定范围的链表
//走n-m-1步,因为是从m位置开始的
for(int i = m; i < n; i++){
if(postnNode == null) return null;
ListNode temp = postnNode.next;
postnNode.next = nNode;
nNode = postnNode;
postnNode = temp;
}
//首位连接逆转之后的链表
mNode.next = postnNode;
premNode.next = nNode;;
return dummpy.next;
}
}