标签:Java

[LeetCode]Swap Nodes in Pairs

[LeetCode]Swap Nodes in Pairs

注意记录前一个节点

//JAVA
public class Solution {
	public ListNode swapPairs(ListNode head) {
		ListNode currNode = head;
		if (head == null)
			return head;
		if (head.next == null)
			return head;
		ListNode newHead = head.next;
		ListNode prev = null;
		boolean flag = true;
		while (flag) {
			if (currNode.next == null)
				break;
			if (currNode.next.next == null)
				flag = false;
			ListNode tempNode = currNode.next;

			currNode.next = tempNode.next;
			tempNode.next = currNode;
			if (prev != null)
				prev.next = tempNode;
			prev = currNode;
			currNode = currNode.next;
		}
		return newHead;
	}
}