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
- 下一篇: 团队项目第二阶段冲刺站立会议01