Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
1 public ListNode swapPairs(ListNode head) {//链表my 2 ListNode nhead = new ListNode(0); 3 nhead.next=head; 4 ListNode cur=head; 5 ListNode pre = nhead; 6 while(null!= cur&&null!=cur.next){ 7 pre.next = cur.next; 8 cur.next=pre.next.next; 9 pre.next.next=cur; 10 pre=cur; 11 cur=cur.next; 12 } 13 return nhead.next; 14 }
方法一样,但可读性更高的代码
public ListNode swapPairs1(ListNode head) { ListNode nhead = new ListNode(0); nhead.next=head; ListNode pre = nhead; while(null!= pre.next&&null!=pre.next.next){ ListNode fitst= pre.next; ListNode second = pre.next.next; pre.next=second; fitst.next=second.next; second.next=fitst; pre=fitst; } return nhead.next; }
相关题
链表反转 LeetCode206 https://www.cnblogs.com/zhacai/p/10429295.html
进阶题
每 k 个节点一组翻转链表 LeetCode25 https://www.cnblogs.com/zhacai/p/10563446.html