zoukankan      html  css  js  c++  java
  • Leetcode: Swap Nodes in Pairs

    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的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧

  • 相关阅读:
    [网站运营]浅谈如何尽可能的避免cms网站被黑
    [CDN]阿里云(企业云解析DNS)让你的博客飞起来
    阿里新生的面试经,与老人分享的职业进阶攻略及规划
    高逼格!程序猿的表白也可以这么浪漫
    程序员表白专属技能,你还不快学起来
    序列上的一些文章
    序列上的一些文章
    最长不下降子序列
    最长不下降子序列
    luoguP2831 愤怒的小鸟
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3719928.html
Copyright © 2011-2022 走看看