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.
//非递归
public class Full { //280ms
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode pre = new ListNode(-1);
pre.next = head;
ListNode p;
head = head.next;
while (pre.next != null){
p = pre.next.next;
if (p != null){
pre.next.next = p.next;
p.next = pre.next;
pre.next = p;
pre = p.next;
}
else {
break;
}
}
return head;
}
}
看到discuss里一位同学写的递归算法,真心觉得很受用!
//递归
public class Full { //250ms
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode p = head , q = head.next;
p.next = swapPairs(q.next);
q.next = p;
return q; //实际返回的就是原始链表的第二个节点head.next
}
}