码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode解题报告--Swap Nodes in Pairs

时间:2015-10-17 12:16:08      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

题目:

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

标签:leetcode   算法   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!