主题思想: 链表翻转:
链表翻转, 链表翻转经典代码:
public ListNode reverseList(ListNode head){
if(head==null||head.next==null) return head;
ListNode prev=null,next=null;
while(head.next!=null){
next=head.next;
head.next=prev;
prev=head;
head=next;
}
// important
head.next=prev;
return head;
}
AC 代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null||head.next==null) return head;
ListNode next=null;
ListNode prevNode=null;
ListNode tail=null;
ListNode pivot=head;
int i=1;
for(i=1;i<m;i++){
if(pivot!=null){
prevNode=pivot;
pivot=pivot.next;
}
}
tail=pivot;
for(;i<n;i++){
if(tail!=null)tail=tail.next;
}
if(tail!=null) next=tail.next;
tail.next=null;
tail=pivot;
if(pivot==head) head=reverseList(pivot);
else prevNode.next=reverseList(pivot);
tail.next=next;
return head;
}
public ListNode reverseList(ListNode head){
if(head==null) return head;
ListNode prev=null;
ListNode next=null;
while(head.next!=null){
next=head.next;
head.next=prev;
prev=head;
head=next;
}
head.next=prev;
return head;
}
}
AC 代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null||head.next==null) return head;
ListNode next=null;
ListNode prevNode=null;
ListNode tail=null;
ListNode pivot=head;
int i=1;
for(i=1;i<m;i++){
if(pivot!=null){
prevNode=pivot;
pivot=pivot.next;
}
}
tail=pivot;
for(;i<n;i++){
if(tail!=null)tail=tail.next;
}
if(tail!=null) next=tail.next;
tail.next=null;
tail=pivot;
if(pivot==head) head=reverseList(pivot);
else prevNode.next=reverseList(pivot);
tail.next=next;
return head;
}
public ListNode reverseList(ListNode head){
if(head==null) return head;
ListNode prev=null;
ListNode next=null;
while(head.next!=null){
next=head.next;
head.next=prev;
prev=head;
head=next;
}
head.next=prev;
return head;
}
}