206.反转链表
public ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode next;
while(head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public ListNode reverseList(ListNode head){
if(head == null || head.next == null) return head;
ListNode new_head = reverseList(head.next);
head.next.next = head;
head.next = null;
return new_head;
}
92.反转链表Ⅱ
public ListNode reverseBetween(ListNode head, int left, int right){
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
for(int i = 1; i< left; i++){
pre = pre.next;
}
ListNode leftnode = pre.next;
ListNode rightnode = pre.next;
for(int i = left; i < right; i++){
rightnode = rightnode.next;
}
ListNode next = rightnode.next;
pre.next = null;
rightnode.next = null;
ListNode node = reverseList(leftnode);
pre.next = node;
leftnode.next = next;
return dummy.next;
}
public ListNode reverseList(ListNode head){
if(head == null || head.next == null) return head;
ListNode new_head = reverseList(head.next);
head.next.next = head;
head.next = null;
return new_head;
}
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
for(int i=1;i<left;i++){
pre = pre.next;
}
ListNode curr = pre.next;
ListNode next = curr.next;
for(int i = left; i< right;i++){
curr.next = next.next;
next.next = pre.next;
pre.next = next;
next = curr.next;
}
return dummy.next;
}
}
public ListNode reverseBetween(ListNode head, int left, int right){
if(left == 1){
return reverseList(head, right);
}
head.next = reverseBetween(head.next, left - 1, right - 1);
return head;
}
ListNode next;
public ListNode reverseList(ListNode head, int right){
if(right == 1){
next = head.next;
return head;
}
ListNode newhead = reverseList(head.next, right - 1);
head.next.next = head;
head.next = next;
return newhead;
}