LeetCode24 Swap Nodes in Pairs 成對交換鏈結表節點,leetcode24交換鏈結

來源:互聯網
上載者:User

LeetCode24 Swap Nodes in Pairs 成對交換鏈結表節點,leetcode24交換鏈結

題目:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

翻譯:

給你一個鏈表,交換每兩個相連的節點。

思路:

就是節點交換問題。只要儲存頭結點,且要理清交換的節點的位置問題。

代碼:

public ListNode swapPairs(ListNode head) {     ListNode root = new ListNode(0);//建立個首節點指向鏈表開始     root.next = head;     ListNode pre = root;//前一個節點     while(head!=null && head.next!=null)     {     ListNode t = head.next.next;     pre.next = head.next;     pre.next.next = head;     head.next = t;     pre = head;     head = t;          }     return root.next;    }


首先得保證該節點和下一個節點存在。

接著就是交換問題。 假設 現在的鏈表是1->2->3->4 。首先建立個root節點,他的next指向頭部。

第一次迴圈:pre指向root,head指向1,要交換12,首先的儲存2的下一個節點3,用t表示,接著使得pre的next為2 ,即head的next;接著2的下一個節點為1,於是乎pre.next.next = head.最後head的下一個為3,即head.next = t。

此時鏈表為2-1-3-4.此時使得指標跳2個。即pre指向1,head指向3即可。然後繼續迴圈實現交換。








聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.