首页 > 其他 > 详细

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

时间:2016-01-16 07:34:45      阅读:164      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!