[leedcode 24] Swap Nodes in Pairs

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.

/**
 * 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) {
        //本题是两个节点进行反转,主要的思想是画图,确定每次循环之前,各个指针的位置
        //注意:1.声明一个新的头结点(很多题都是这种方法),只需在返回时注意返回新头结点的next即可
        //2.注意当链表为空,以及只有一个节点时的处理方法
        if(head==null||head.next==null)
            return head;
        ListNode newHead=new ListNode(-1);
        ListNode last=newHead;
        ListNode s=head;
        ListNode t=head;
        while(t!=null&&t.next!=null){
            t=s.next.next;
            last.next=s.next;
            last.next.next=s;
            s.next=t;
            last=s;
            s=t;
        }
        return newHead.next;
        
    }
}

 

posted @ 2015-07-08 13:55  ~每天进步一点点~  阅读(122)  评论(0编辑  收藏  举报