首页 > 其他 > 详细

[Leetcode] Swap Nodes in Pairs

时间:2015-12-03 00:08:33      阅读:277      评论: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.

该题只要一个指针,每次指向需要交换的两个节点的第一个节点的前一个节点,有了这个指针,需要操作的后面几个节点就都能找到。交换完当前的一对节点后,将该指针后移两个节点,使其指向下次要交换的两个节点的前一个节点,直到后面没有节点或者只有一个节点。另外,新建一个头节点会有利于头指针为空这种特殊情况的处理。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode swapPairs(ListNode head) {
11         ListNode dummy = new ListNode(0), prev = dummy, tmp;
12         dummy.next = head;
13         while(prev.next != null && prev.next.next != null) {
14             tmp = prev.next.next.next;
15             prev.next.next.next = prev.next;
16             prev.next = prev.next.next;
17             prev.next.next.next = tmp;
18             prev = prev.next.next;
19         }
20         
21         return dummy.next;
22     }
23 }

 

[Leetcode] Swap Nodes in Pairs

原文:http://www.cnblogs.com/seagoo/p/5014606.html

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