Leetcode 24. Swap Nodes in Pairs
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 24. Swap Nodes in Pairs
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
不定期更新leetcode解題java答案。
采用pick one的方式選擇題目。
本題很簡單,大致翻譯過來的意思是將單鏈表相鄰節點互換節點位置。額外的要求是使用O(1)空間,以及不修改節點值,僅對節點位置修改。意思就是防止使用互換節點值的方式,省去交換節點位置的操作,這種取巧的方法。
思路很簡單,進行節點next指針交換即可。直接粘代碼:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/ public class Solution {public ListNode swapPairs(ListNode head) {ListNode pre = new ListNode(0);pre.next = head;ListNode node = pre;while(node != null){ListNode pre_head = node;ListNode now = node.next;if(now == null)break;node = node.next.next;if(node != null){now.next = node.next;pre_head.next = node;node.next = now;node = now;}}return pre.next;} }
轉載于:https://www.cnblogs.com/zslhq/p/5559661.html
總結
以上是生活随笔為你收集整理的Leetcode 24. Swap Nodes in Pairs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android分包方案multidex
- 下一篇: 长豆角的家常做法?