Middle-题目25:24. Swap Nodes in Pairs

原创 2016年05月31日 15:47:59

题目原文:
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.
题目大意:
给一个单链表,两两交换相邻节点。
题目分析:
用Two Pointers,分别指向头结点和第二个节点,每次移动两步,注意处理结点个数为奇数(最后一次的时候p2->next为空,再取next会报错)的特殊情况。
源码:(language:java)

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) // This list has only 0 or 1 node.
            return head;    
        ListNode l1=head,l2=head.next;
        while(l1!=null && l2!=null) { 
            int temp=l1.val;
            l1.val=l2.val;
            l2.val=temp;
            l1=l1.next.next;
            l2=l2.next;
            if(l2==null)
                break;
            else
                l2=l2.next;
        }
        return head;
    }
}

成绩:
0ms,beats 13.35%,众数0ms,86.65%
Cmershen的碎碎念:
这题很水,不知道为什么出现在Middle里面。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode24 Swap Nodes in Pairs 25. Reverse Nodes in k-Group详解

/************************************************************************ * * Given a linked lis...

LeetCode24. Swap Nodes in Pairs

LeetCode24. Swap Nodes in Pairs

( Leetcode 24) Swap Nodes in Pairs

题目:Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. ...

24. Swap Nodes in Pairs [easy] (Python)

题目链接https://leetcode.com/problems/swap-nodes-in-pairs/题目原文 Given a linked list, swap every two adj...

LeetCode 24. Swap Nodes in Pairs 解题报告

LeetCode 24. Swap Nodes in Pairs 解题报告题目描述Given a linked list, swap every two adjacent nodes and retu...

leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法

Swap Nodes in Pairs  Given a linked list, swap every two adjacent nodes and return its head. F...

LeetCode之24----Swap Nodes in Pairs

题目: Given a linked list, swap every two adjacent nodes and return its head. For example, Gi...

[leetcode: Python]24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.For example, Given 1->2->3->...
  • NXHYD
  • NXHYD
  • 2017-05-19 15:37
  • 120

LeetCode 24. Swap Nodes in Pairs

题目Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2...

leetcode-24 Swap Nodes in Pairs

问题描述地址:https://leetcode.com/problems/swap-nodes-in-pairs/ 描述: Given a linked list, swap every two...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)