两两交换链表中的节点
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode p=head.next;
head.next=swapPairs(p.next);
p.next=head;
return p;
}
删除链表的倒数第 N 个结点
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next=head;
ListNode fast=dummy;
ListNode slow=dummy;
for(int i=0;i<n;i++)fast=fast.next;
while(fast.next!=null){
slow=slow.next;
fast=fast.next;
}
slow.next=slow.next.next;
return dummy.next;
}
链表相交
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p1=headA,p2=headB;
while(p1!=p2){
if(p1==null)p1=headB;
else p1=p1.next;
if(p2==null)p2=headA;
else p2=p2.next;
}
return p1;
}
环形链表
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next=head;
ListNode fast=dummy;
ListNode slow=dummy;
for(int i=0;i<n;i++)fast=fast.next;
while(fast.next!=null){
slow=slow.next;
fast=fast.next;
}
slow.next=slow.next.next;
return dummy.next;
}