[Leetcode] 24. 兩兩交換連結串列中的節點 java
阿新 • • 發佈:2018-11-08
給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。
示例:
給定1->2->3->4
, 你應該返回2->1->4->3
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode swapPairs(ListNode head) {//不設定dummyHead得到的結果是2,4 17、20行 ListNode dummyHead=new ListNode(0); dummyHead.next=head; head=dummyHead; while(head.next!=null&&head.next.next!=null){ ListNode node1=head.next; ListNode node2=head.next.next; head.next=node2; node1.next=node2.next; node2.next=node1; head=node1; } return dummyHead.next; } }