leetcode------Swap Nodes in Pairs

标题: Swap Nodes in Pairs
通过率: 32.5
难度: 中等

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-》3-》4

再操作3,4交换后要将2指向4,不能再指向3了,另外,再第一次交换的时候要把链表的入口换成2,具体细节操作见代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode swapPairs(ListNode head) {
14         if(head==null||head.next==null)return head;
15         ListNode res=head;
16         ListNode first=head,second=head.next,pre=null;
17         int i=0;
18         ListNode tmp=new ListNode(-1);
19         while(second!=null){
20             tmp.next=second.next;
21             second.next=first;
22             first.next=tmp.next;
23             if(i==0)res=second;
24             if(pre!=null)pre.next=second;
25             pre=first;
26             first=first.next;
27             if(first==null)break;
28             second=first.next;
29             i=1;
30             
31         }
32         return res;
33     }
34 }

 

posted @ 2015-03-12 22:24  pku_smile  阅读(145)  评论(0编辑  收藏  举报