Skip to content
New issue

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

两两交换链表中的节点 #47

Open
louzhedong opened this issue Sep 4, 2018 · 0 comments
Open

两两交换链表中的节点 #47

louzhedong opened this issue Sep 4, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处: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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant