心得:第一次忘了把头指针和参数关联,链表问题要善于用头指针,简单
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode swapPairs(ListNode head) { 11 if(head==null) 12 return null; 13 ListNode rHead=new ListNode(-1); 14 rHead.next=head; ///不要忘记赋值。。。。。 15 ListNode tmpHead=rHead; 16 ListNode tmpNode=rHead.next; 17 while(tmpNode!=null&&tmpNode.next!=null) 18 { 19 tmpHead.next=tmpNode.next; 20 tmpNode.next=tmpHead.next.next; 21 tmpHead.next.next=tmpNode; 22 tmpHead=tmpNode; 23 tmpNode=tmpHead.next; 24 } 25 return rHead.next; 26 } 27 }
原文:https://www.cnblogs.com/pc-m/p/10883633.html