题目描述:给定一个链表,每交换两个相邻节点并返回其头部。
您不能修改列表节点中的值,只能修改节点本身。
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
public static ListNode swapPairs(ListNode head) {
if ((head == null) || (head.next == null))
return head;
ListNode Next = head.next;
head.next = swapPairs(head.next.next);
Next.next = head;
return Next;
}
public static ListNode swapPairs2(ListNode head) {
if (head == null)
return null;
ListNode helper = new ListNode(0);
helper.next = head;
ListNode pre = helper;
ListNode cur = head;
while (cur != null && cur.next != null) {
ListNode next = cur.next.next;
cur.next.next = cur;
pre.next = cur.next;
if (next != null && next.next != null)
cur.next = next.next;
else
cur.next = next;
pre = cur;
cur = next;
}
return helper.next;
}
本文详细介绍了两种在链表中交换相邻节点的算法实现。通过递归和迭代的方法,不改变节点值,仅调整节点链接,完成每对相邻节点的位置交换。提供了完整的Java代码示例,适用于理解链表操作及算法设计。
676

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



