Q19 LeetCode24 两两交换链表节点

1.注意节点交换顺序,以防节点丢失

2.ListNode dummy = new ListNode(0, head); 定义空指针,并指向head节点  好语句

3.还是虚拟头结点好用

 

 1 class Solution {
 2     public ListNode swapPairs(ListNode head) {
 3          ListNode dummy = new ListNode(0, head);
 4         ListNode cur=pre;
 5         ListNode tem1=null;
 6         ListNode tem2=null;
 7         while(cur.next!=null&&cur.next.next!=null){
 8             tem1=cur.next;
 9             tem2=cur.next.next;
10             cur.next=tem2;
11             tem1.next=tem2.next;
12             tem2.next=tem1;    
13             cur= tem1;
14 
15         }
16         return pre.next;
17     }
18 }

 

posted @ 2024-06-09 10:46  清川1  阅读(16)  评论(0)    收藏  举报