Problem:
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Explanation:
给定一个链表,交换相邻的两个结点,两个两个交换,但是不能通过改变结点的值。
My Thinking:
正向遍历链表,设置pre,cur,next三个指针,通过改变三个指针之间的指向关系对cur和next进行交换,时间复杂度O(n)。
My Solution:
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode pre=new ListNode(-1);
pre.next=head;
ListNode cur=head;
ListNode next;
if(head==null)
next=null;
else
next=head.next;
while(next!=null){
//结点交换
pre.next=next;
if(cur==head)
head=next;
cur.next=next.next;
next.next=cur;
//指针后移
pre=cur;
if(pre.next!=null)
next=pre.next.next;
else
next=null;
cur=pre.next;
}
return head;
}
}
Optimum Thinking:
- 使用递归,从后向前两个两个比较,返回交换后的前一个元素,时间复杂度为O()
- 和My Thinking一样
Optimum Solution:
(1)
我写的:
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode next=swapPairs(head.next.next);//两个两个递归,返回交换后的前一个结点
ListNode newhead=head.next;//设置一个新头(两个结点交换后的第一个元素,也就是交换前的第二个元素head.next)
head.next.next=head;
head.next=next;
return newhead;
}
}
讨论中写的:
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;
}
}
讨论中写的答案更简洁一点,思路完全一样。
(2)同My Solution。
庆祝一下第一次自己把递归写出来!