链表专项
反转题型
1.206. 反转链表(反转整个单链表)
方法一.双指针法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur=head;
ListNode pre=null;//pre指向cur的前一位
ListNode temp=null;
while(cur!=null){
temp=cur.next;//保存cur的下一个节点
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}
}
方法二.递归法
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode last=reverseList(head.next);
head.next.next=head;
head.next=null;
return last;
}
}
2.92. 反转链表 II(反转一部分链表)
方法一.递归
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if(left==1){
return reverseN(head,right);
}
head.next=reverseBetween(head.next,left-1,right-1);
return head;
}
ListNode successor=null;
public ListNode reverseN(ListNode head,int n){
if(n==1){
successor=head.next;
return head;
}
ListNode last=reverseN(head.next,n-1);
head.next.next=head;
head.next=successor;
return last;
}
}
方法二.穿针引线
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode pre=dummy;
for(int i=0;i<left-1;i++){
pre=pre.next;
}
ListNode cur=pre.next;
ListNode next;
for(int i=left;i<right;i++){
next=cur.next;
cur.next=next.next;
next.next=pre.next;
pre.next=next;
}
return dummy.next;
}
}
3.两两交换链表中的节点
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode cur=dummy;
//针对偶数节点cur.next!=null,针对奇数节点cur.next.next!=null
while(cur.next!=null&&cur.next.next!=null){
ListNode temp=cur.next;
ListNode temp1=cur.next.next.next;
cur.next=cur.next.next;
cur.next.next=temp;
temp.next=temp1;
cur=cur.next.next;
}
return dummy.next;
}
}```