问题描述
地址:https://leetcode.com/problems/swap-nodes-in-pairs/
描述:
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.
翻译:给出一个linked list,交换两个相邻的node后返回head
问题解析
初步想法:
(1)如果想交换节点位置,首先我们需要两个指针,一个标记当前及诶点(current),一个标记当前节点的下一个节点(next)
(2)交换current和next的next节点即可
然而这样直接交换显然会有个问题
解析代码
public class SwapNodesinPairs2 {
public static void main(String[] args) {
ListNode listNode = ListNode.init();
ListNode result = swapPairs(listNode);
System.out.println("1");
}
public static ListNode swapPairs(ListNode head) {
ListNode current = head;
if(current == null){
return head;
}
ListNode next = head.next;
if(next == null){
return head;
}
//需要注意的地方1 将表头重置到第二个节点,否则表会断
//比方说 1->2->3->4 如果不重置表头最终得到的结果将会是 1->3->4
head = next;
//tmp用来记录上一次交换前末尾节点的位置
ListNode tmp = null;
while (current != null && next != null) {
current.next = next.next;
next.next = current;
if (tmp != null) {
tmp.next = next;
}
tmp = current;
current = current.next;
if (current != null) {
next = current.next;
}
}
return head;
}
}