题目地址:24. 两两交换链表中的节点
看到这题目也没想太多,常规思维大概就是这样:
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode p = head;
ListNode q=head.next;
ListNode pre=head;
int count=0;
while(p!=null&&q!=null){
if (count == 0){
p.next=q.next;
q.next=p;
pre=p;
head=q;
}
if (count>0){
p.next=q.next;
q.next=p;
pre.next=q;
pre=p;
}
count++;
p=p.next;
if(p!=null)
q=p.next;
}
return head;
}
}
结果:
看着还可以啊,但确实代码量有点大,显得冗余,直到看到官方的递归方法,短小精悍,啥时候我能想出这么美观的代码……
class Solution {
public ListNode swapPairs(ListNode head) {
// 如果链表为空或只有一个节点
if ((head == null) || (head.next == null)) {
return head;
}
// 初始化要交换的两个节点
ListNode firstNode = head;
ListNode secondNode = head.next;
// 交换
firstNode.next = swapPairs(secondNode.next);
secondNode.next = firstNode;
// 返回交换完成后的首节点
return secondNode;
}
}
结果:
我以为递归时间会慢一点,结果……有点东西。
第二种官方的方法是迭代法,但貌似就是我最初写的那个代码的意思,只是简化了,我在第一次交换的时候设了一个计数器,其实没有必要,只是没有想到如何优化……
class Solution {
public ListNode swapPairs(ListNode head) {
// dummy节点为head节点的前驱
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prevNode = dummy;
while ((head != null) && (head.next != null)) {
// 要交换的两个节点
ListNode firstNode = head;
ListNode secondNode = head.next;
// 交换
prevNode.next = secondNode;
firstNode.next = secondNode.next;
secondNode.next = firstNode;
// 重置前驱节点
prevNode = firstNode;
head = firstNode.next; // jump
}
// R返回新的头节点
return dummy.next;
}
}
结果:
感觉没多大区别……不过确实好看了,以后注意美观。