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.
题目链接:https://leetcode.com/problems/swap-nodes-in-pairs/description/
迭代法:四个数字作为一组,在纸上画画即可
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode helper = new ListNode(0);
helper.next = head.next;
ListNode pre = head, cur = head, tmp = head;
while (pre != null && pre.next != null) {
cur = pre.next;
tmp = cur;
cur = cur.next;
tmp.next = pre;
if (cur == null) {
pre.next = null;
break;
}
if (cur.next == null) {
pre.next = cur;
cur.next = null;
break;
}
pre.next = cur.next;
pre = cur;
}
return helper.next;
}
}
递归法:真的好写。。。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head.next;
head.next = swapPairs(cur.next);
cur.next = head;
return cur;
}
}