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

Swap Nodes in Pairs; Data Structure; Linked List; Pointer;

时间:2016-01-16 07:35:12      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

注意用指针记录节点的前一个节点位置。

代码:

/**
 * 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) {
        if(head == null || head.next == null) return head;
        ListNode nex = head.next.next;
        ListNode newHead = head.next;
        head.next.next = head;
        head.next = nex;
        ListNode prev = head;
        ListNode cur = nex;
        while(cur != null && cur.next != null){
            nex = cur.next.next;
            prev.next = cur.next;
            cur.next.next = cur;
            cur.next = nex;
            prev = cur;
            cur = nex;
        }
        return newHead;
    }
}

  

 

Swap Nodes in Pairs; Data Structure; Linked List; Pointer;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5134890.html

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