反转链表(LeetCode209)
初级反转即是用两个指针进行反转
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode before=head,after=head.next;
while(after!=null){
ListNode temp=after.next;
after.next=before;
before=after;
after=temp;
}
head.next=null;
return before;
}
}
反转链表II(LeetCode92)
中级反转,即先遍历找到要反转的点,再利用前一道题的反转策略进行反转
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode a=dummy;
for(int i=0;i<left-1;i++) a=a.next;
ListNode b=a.next,c=b.next;
for(int i=left;i<right;i++){
ListNode temp=c.next;
c.next=b;
b=c;
c=temp;
}
a.next.next=c;
a.next=b;
return dummy.next;
}
}
K个一组翻转链表(LeetCode25)
就是在中级的基础上,K个一组进行枚举反转
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode a=dummy;
while(a!=null){
ListNode p=a;
for(int i=0;i<k&&p!=null;i++) p=p.next;
if(p==null) break;
ListNode b=a.next,c=b.next;
for(int i=0;i<k-1;i++){
ListNode temp=c.next;
c.next=b;
b=c;c=temp;
}
a.next.next=c;
a.next=b;
for(int i=0;i<k;i++) a=a.next;
}
return dummy.next;
}
}