/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
// ListNode dummyNode=new ListNode(0,head);//虚拟头节点
// ListNode f=dummyNode;
// while(f.next!=null&&f.next.next!=null){
// ListNode s=f.next;
// ListNode t=s.next;//因为节点反转 s、t每次会换位置,在循环里定义是防止s和t的位置来回变,
// s.next=t.next;//没有指针指着会丢,所以先存t后面的
// t.next=s;
// f.next=t;
// f=f.next.next;
// }
// return dummyNode.next;
ListNode dummy=new ListNode(-1,head);
ListNode cur=dummy;
while(cur.next!=null&&cur.next.next!=null){
ListNode temp=cur.next;
ListNode temp2=temp.next.next;
cur.next=temp.next;
temp.next.next=temp;
temp.next=temp2;
cur=cur.next.next;
}
return dummy.next;
}
}
- 删除链表的倒数第 N 个结点
要删一个节点操作指针一定是前面的节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy=new ListNode(-1,head);
ListNode slow=dummy;
ListNode fast=dummy;
for(int i=1;i<=n+1;i++){//从dummy往后移动四次
fast=fast.next;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
slow.next=slow.next.next;//slow.next(指向slow)=slow.next.next;(查找slow.next.next)
return dummy.next;
}
}
面试题 02.07. 链表相交
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A= headA;
ListNode B= headB;
int sizeA=0;
int sizeB=0;
while(A!=null){//加完再指向下一个
sizeA++;
A=A.next;
}
while(B!=null){//加完再指向下一个
sizeB++;
B=B.next;
}
A=headA;//一定要!!!!!!!别忘了
B=headB;
if(sizeB>sizeA){// 让curA为最长链表的头,lenA为其长度
int temp=sizeB;
sizeB=sizeA;
sizeA=temp;
ListNode tempNode=A;
A=B;
B=tempNode;
}
int gap=sizeA-sizeB;
while(gap>0){
A=A.next;
gap--;
}
while(A!=null){
if(A==B){
return A;
}
A=A.next;
B=B.next;
}
return null;
}
}
142.环形链表II
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){//因为是两步两步跳的(链表个数为单双数的情况)
fast=fast.next.next;
slow=slow.next;
if(slow==fast){
ListNode newNode=head;
while(newNode!=slow){
slow=slow.next;
newNode=newNode.next;
}
return newNode;
}
}
return null;
}
}