题目要将相邻两个节点交换但是不能只交换数值。
1. 我的方法 循环
1)需要注意判断是否是null,凡是要调用next就要注意了!
2)注意交换两个节点之后,node指向的下一个并不是当前后面链表的头(因为后面也要交换),所以应该判断下后面会不会继续交换,如果是的话就要指向下下个,不然就直接指向下一个。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode node = head;
if(node==null || node.next==null)
return node;
ListNode pre = new ListNode(0);
pre.next = node.next;
while(node!=null && node.next!=null){
ListNode tmp = node.next.next;
node.next.next = node;
if(tmp!=null &&tmp.next != null)
node.next = tmp.next;//这几行对应第二个注意点
else
node.next = tmp;
node = tmp;
}
return pre.next;
}
}
2. 使用递归
public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}