1. 程式人生 > >[leetcode]24. Swap Nodes in Pairs交換鏈表的節點

[leetcode]24. Swap Nodes in Pairs交換鏈表的節點

運行 鏈表 log tle first body blog 交換 ext

感覺這個題後臺的運行程序有問題,一開始自己想的是反轉鏈表那道題的方法,只是隔一個節點執行一次,但是沒有通過,TLE了,但是很奇怪,並沒有死循環,就是最後返回的時候超時。

最後的思路就是很簡單的進行交換,設置一個頭結點前邊的0節點先把第三個節點接到第一個上邊,然後把第一個接到第二個上,然後把第二個節點接到0節點上,然後把當前節點設置成第一個節點(現在是第二個,而且是下次交換的0節點)

public ListNode swapPairs(ListNode head) {
        if (head==null) return null;
        ListNode dummy = new ListNode(0);
        dummy.next 
= head; ListNode cur = dummy; while (cur.next!=null&&cur.next.next!=null) { ListNode first = cur.next; ListNode sec = cur.next.next; first.next = sec.next; sec.next = first; cur.next = sec; cur = first; }
return dummy.next; }

[leetcode]24. Swap Nodes in Pairs交換鏈表的節點