链表小结:
1/链表的性质,有指针
2/对应删减方法,改变指向。注意理清方向,避免死循环和值丢失
3./注意起始点,常用dummyHead 来规避
4/注意循环while()的终止条件,一般是cur!=null
5.需要复盘,和补上剩下的02.07链表香蕉和 142.环形链表
24. 两两交换链表中的节点
中等
相关企业
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
/**
* 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) {
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode dummyHead = new ListNode(0);
dummyHead.next=head;
ListNode pre=dummyHead;
ListNode temp=null;
while(pre.next!=null&&pre.next.next!=null){
temp=head.next.next;
pre.next= head.next;
head.next.next=head;
head.next=temp;
pre=head;
head=head.next;
}
return dummyHead.next;
}
}