标签:leetcode
https://oj.leetcode.com/problems/swap-nodes-in-pairs/
http://fisherlei.blogspot.com/2013/01/leetcode-swap-nodes-in-pairs.html
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode a = head; ListNode b = head.next; ListNode newhead = b; ListNode pre = null; while (a != null && b != null) { // a -> b // swap a and b ListNode next = b.next; a.next = next; b.next = a; if (pre != null) pre.next = b; pre = a; a = next; if (a != null) b = a.next; } return newhead; } }
[LeetCode]24 Swap Nodes in Pairs
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1598423