We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
出处:LeetCode 算法第24题 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 示例: 给定 1->2->3->4, 你应该返回 2->1->4->3. 说明: 你的算法只能使用常数的额外空间。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
出处:LeetCode 算法第24题
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:
创建临时的节点,使其next为head,顺序判断链表中相邻的两个元素,并将他们进行交换。
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var swapPairs = function (head) { if (head == null || head.next == null) { return head; } var first = new ListNode(0); first.next = head; var res = first; while (first.next != null && first.next.next != null) { var one = first.next; var two = first.next.next; one.next = two.next; two.next = one; first.next = two; first = first.next.next; } return res.next; };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思路
创建临时的节点,使其next为head,顺序判断链表中相邻的两个元素,并将他们进行交换。
解答
The text was updated successfully, but these errors were encountered: