首页 > 其他 > 详细

LeetCode解题报告--Swap Nodes in Pairs

时间:2015-10-17 12:13:55      阅读:596      评论:0      收藏:0      [点我收藏+]

题目:

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.
原题:https://leetcode.com/problems/swap-nodes-in-pairs/

分析:题意要求将给定的链表,相邻的结点交换位置,并返回变化后的链表。
基本思路利用指针移位法,注意考虑特殊情况,如链表为空,链表长度为0,1,2等。
如下图是思路的示意:
技术分享
不同颜色表示不同次的循环过程。

java代码 Accepted:

/**
 * 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 p;
        ListNode q;
        ListNode k;
        p = head;
        q = p.next;
        k = q.next;

        head = head.next;
        while (q != null) {
            q.next = p;

            if(k != null && k.next != null){
                p.next = k.next;
                p = k;
                q = k.next;
                k = k.next.next;
            }else{
                p.next = k;
                q = null;
                k = null;
            }
            /*p = k;

            if(k != null){
                q = k.next;
            }else{
                q = null;
            }

            if(k != null && k.next != null){
                k = k.next.next;
            }else{
                k = null;
            }*/
        }
        return head;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。个人github代码空间:https://github.com/gannyee

LeetCode解题报告--Swap Nodes in Pairs

原文:http://blog.csdn.net/github_27609763/article/details/49202323

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!