标签:
问题:
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 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode swapPairs(ListNode head) { 11 ListNode dummy = new ListNode(0), prev = dummy, tmp; 12 dummy.next = head; 13 while(prev.next != null && prev.next.next != null) { 14 tmp = prev.next.next.next; 15 prev.next.next.next = prev.next; 16 prev.next = prev.next.next; 17 prev.next.next.next = tmp; 18 prev = prev.next.next; 19 } 20 21 return dummy.next; 22 } 23 }
[Leetcode] Swap Nodes in Pairs
标签:
原文地址:http://www.cnblogs.com/seagoo/p/5014606.html