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://oj.leetcode.com/problems/swap-nodes-in-pairs/
题目:给定一个链表,交换两个邻接节点并返回。
你的算法只能使用常数空间。不能修改表中的值,只有节点自身可以改变。
思路:首先,直接交换两个节点的值。可以通过,但是不符合要求。
public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode back = head; while (back != null) { if (back.next != null) { int val = back.val; back.val = back.next.val; back.next.val = val; back = back.next.next; } else break; } return head; }
第2种方法:先设置一个虚拟的头节点,防止为空。再交换节点的引用。
public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode pre = dummy; while (head != null && head.next != null) { ListNode tmp = head.next.next; pre.next = head.next; head.next.next = head; head.next = tmp; pre = head; head = tmp; } return dummy.next; }
LeetCode——Swap Nodes in Pairs,布布扣,bubuko.com
时间: 2024-10-12 06:55:47