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

【leetcode】24. Swap Nodes in Pairs

时间:2016-07-05 01:02:14      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

Given a linked list, swap every two adjacent nodes and return its head.

解题分析:

解题思路很简单,就是先两两扫描,然后调换顺序即可。这道题的难点在于每个节点的next域指向问题,所以解这样的题最好可以在纸上写一下交换的步骤就不难实现

具体代码:

 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 static ListNode swapPairs(ListNode head) {
11           if(head==null)
12               return null;
13           if(head.next==null){
14               return head;
15           }
16           if(head.next.next==null){
17               ListNode current=head.next;
18               current.next=head;
19               head=head.next;
20               current.next.next=null;
21               return head;
22           }
23           ListNode pre=null;
24           ListNode current=head.next;
25           head.next=current.next;
26           current.next=head;
27           head=current;
28           current=head.next;
29           pre=current;
30           current=pre.next;
31           while(current!=null && current.next!=null){
32               pre.next=current.next;
33               current.next=current.next.next;
34               pre.next.next=current;
35               pre=current;
36               current=pre.next;
37           }
38           return head;  
39      }
40     
41 }

 

【leetcode】24. Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/godlei/p/5642167.html

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