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;
}
}

本文介绍了一种链表操作技巧——成对交换相邻节点的方法。通过两种实现方式:迭代法与递归法,详细解释了如何在常数空间内完成这一任务,而不改变链表中的元素值。
628

被折叠的 条评论
为什么被折叠?



