【leetcode】24. Swap Nodes in Pairs

题目描述:

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 }
原文地址:https://www.cnblogs.com/godlei/p/5642167.html