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

对链表进行插入排序 #122

Open
louzhedong opened this issue Jan 23, 2019 · 0 comments
Open

对链表进行插入排序 #122

louzhedong opened this issue Jan 23, 2019 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第147题

对链表进行插入排序。

img
插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。

插入排序算法:

  1. 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
  2. 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
  3. 重复直到所有输入数据插入完为止。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4

示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

思路

通过标记,依次遍历所有的节点,将需要交换的进行交换

解答

function ListNode(val) {
  this.val = val;
  this.next = null;
}
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var insertionSortList = function (head) {
  if (!head || !head.next) {
    return head;
  }
  var virtual = new ListNode(0);
  virtual.next = head;
  var index = 1;
  var prev = head;
  var current = head.next;

  while (current) {
    var exchange = false;
    var start = virtual.next;
    if (current.val <= start.val) {
      virtual.next = current;
      prev.next = current.next;
      current.next = start;
      current = prev.next;
      exchange = true;
    } else {
      var front = start;
      start = start.next;
      var flag = 1;
      while (flag < index) {
        if (current.val <= start.val) {
          prev.next = current.next;
          front.next = current;
          current.next = start;
          current = prev.next;
          exchange = true;
          break;
        }
        flag++;
        front = front.next;
        start = start.next;
      }
    }
    if (!exchange) {
      current = current.next;
      prev = prev.next;
    }
    index++;
  }
  return virtual.next;
};


var head = new ListNode(-1);
var start = head;
head.next = new ListNode(5);
head = head.next;
head.next = new ListNode(3);
head = head.next;
head.next = new ListNode(4);
head = head.next;
head.next = new ListNode(0);

console.log(insertionSortList(start));
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