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

    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.

    把一个链表中的每一对节点对换(不能只换值)

    /**
     * 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) {
        if(head == null || head.next == null)   
            return head;
     
        ListNode h = new ListNode(0);
        h.next = head;
        ListNode p = h;
     
        while(p.next != null && p.next.next != null){
            //use t1 to track first node
            ListNode t1 = p;
            p = p.next;
            t1.next = p.next;
     
            //use t2 to track next node of the pair
            ListNode t2 = p.next.next;
            p.next.next = p;
            p.next = t2;
        }
     
        return h.next;
    }
    }

    解题思路:这题主要涉及到链表的操作,没什么特别的技巧,注意不要出错就好。最好加一个头结点,操作起来会很方便。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param a ListNode
        # @return a ListNode
        def swapPairs(self, head):
            if head == None or head.next == None:
                return head
            dummy = ListNode(0); dummy.next = head
            p = dummy
            while p.next and p.next.next:
                tmp = p.next.next
                p.next.next = tmp.next
                tmp.next = p.next
                p.next = tmp
                p = p.next.next
            return dummy.next
  • 相关阅读:
    使用T4模板生成POCO类
    MiniProfiler工具介绍
    程序集和反射(C#)
    按自己的想法去理解事件和泛型(C#)
    WebAPI性能优化之压缩解压
    那些年困扰我们的委托(C#)
    HTML5笔记2——HTML5音/视频标签详解
    HTML5笔记1——HTML5的发展史及标签的改变
    工作中常用的js、jquery自定义扩展函数代码片段
    记一次.NET代码重构
  • 原文地址:https://www.cnblogs.com/zxqstrong/p/5287804.html
Copyright © 2011-2022 走看看