力扣原题:两两交换链表中的节点
思路解析:在此题目中要求只能交换节点,不能交换节点内部的值,说明需要对各个节点的next域的指向进行更改;假设此时有四个节点,需要将1、2节点交换,3、4节点交换,即是将1节点的前驱节点指向2节点,2节点指向1节点,1节点再指向3节点(2节点的后继节点)。
但是,在做题过程中任然需要考虑特殊情况:链表中是奇数节点或者只有一个节点甚至没有节点的情况。于是得出以下代码:
public class Solution24 {
public ListNode swapPairs(ListNode head) {
if (head == null){
return null;
}else if (head.next == null){
return head;
}
ListNode newhead = new ListNode(-1);
newhead.next = head;
ListNode ret = newhead;
ListNode cur = head.next;
while (head != null && head.next != null){
ret.next = cur;
head.next = cur.next;
cur.next = head;
ret = head;
head = head.next;
if (head != null) {
cur = head.next;
}
}
return newhead.next;
}
}
在上述代码中将一个节点、无节点的情况分开来讨论,虽然最后结果是正确的,但是未免过于冗余,于是便得出一下简化代码:
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode tmp = newHead;
while (tmp.next != null && tmp.next.next != null) {
ListNode node1 = tmp.next;
ListNode node2 = tmp.next.next;
temp.next = node2;
node1.next = node2.next;
node2.next = node1;
temp = node1;
}
return newHead.next;
}
}