Leetcode: Swap Nodes in Pairs
LeetCode in swap nodes Pairs
2023-09-11 14:14:08 时间
1 Given a linked list, swap every two adjacent nodes and return its head. 2 3 For example, 4 Given 1->2->3->4, you should return the list as 2->1->4->3. 5 6 Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
这道题属于链表操作的题目,思路比较清晰,就是每次跳两个节点,后一个接到前面,前一个接到后一个的后面,最后现在的后一个(也就是原来的前一个)接到下下个结点(如果没有则接到下一个)。坑爹地多次过,全都是写程序时不注意的小问题,书写习惯还需要进一步改善。遇到的bug有:忘记return语句;定义ListNode runner = head.next,却将判断head==null的情况放在这句之后; 忘记了新的head将不会是原来的那个head,而是head.next;
所以以后遇到runner.next.next的情况要先确保runner.next != null; 遇到runner.next的情况要先确保runner != null
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode swapPairs(ListNode head) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 ListNode dummy = new ListNode(0); 17 dummy.next = head; 18 ListNode curr = dummy; 19 ListNode node1 = null; 20 ListNode node2 = null; 21 22 while(curr.next!=null && curr.next.next!=null){ 23 node1 = curr.next; 24 node2 = node1.next; 25 ListNode next =node2.next; 26 curr.next = node2; 27 node2.next = node1; 28 node1.next = next; 29 curr=node1; 30 } 31 return dummy.next; 32 } 33 }
这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧
相关文章
- Leetcode: Word Pattern
- LeetCode Add Binary |My Solution
- [LeetCode][Java] Populating Next Right Pointers in Each Node II
- JS Leetcode 278. 第一个错误的版本 题解分析
- JS leetcode 有多少小于当前数字的数字 解题分析,你应该了解的桶排序
- [LeetCode] Reverse Words in a String
- [LeetCode] Power of Two
- 【开始刷LeetCode】474. 一和零
- [LeetCode]剑指 Offer 22. 链表中倒数第k个节点
- LeetCode Search in Rotated Sorted Array 在旋转了的数组中查找
- 【LeetCode】268. Missing Number
- 【LeetCode】198. House Robber
- 【LeetCode】84. Largest Rectangle in Histogram
- 【LeetCode】103. Binary Tree Zigzag Level Order Traversal
- 【LeetCode】115. Populating Next Right Pointers in Each Node (2 solutions)
- [LeetCode] 1261. Find Elements in a Contaminated Binary Tree 在受污染的二叉树中查找元素
- [LeetCode] 1041. Robot Bounded In Circle 困于圆圈路径中的机器人
- [LeetCode] 961. N-Repeated Element in Size 2N Array 在大小为2N的数组中重复N次的数字
- [LeetCode] 845. Longest Mountain in Array 数组中最长的山
- [LeetCode] 789. Escape The Ghosts 逃离鬼魂
- [LeetCode] 488. Zuma Game 祖玛游戏
- [LeetCode] 532. K-diff Pairs in an Array 数组中差为K的数对
- [LeetCode] 369. Plus One Linked List 链表加一运算
- [LeetCode] 117. Populating Next Right Pointers in Each Node II 每个节点的右向指针之二
- Leetcode——24. Swap Nodes in Pairs
- leetcode 88. Merge Sorted Array 归并两个有序数组