LeetCode解题报告--Swap Nodes in Pairs

来源:互联网 发布:手机网络管理软件 编辑:程序博客网 时间:2024/06/05 19:48

题目:

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;    }}
0 0
原创粉丝点击