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

分隔链表 #68

Open
louzhedong opened this issue Oct 5, 2018 · 0 comments
Open

分隔链表 #68

louzhedong opened this issue Oct 5, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第86题

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

思路

创建两个空的链表,遍历原链表,将小于目标的结点放置于其中一个链表,将大于等于的结点放置于另一个链表,再将两个链表拼接在一起

解答

function ListNode(val) {
  this.val = val;
  this.next = null;
}

var partition = function (head, x) {
  var temp = new ListNode();
  var flag = new ListNode();
  var big = temp;
  var small = flag;
  while (head != null) {
    if (head.val >= x) {
      temp.next = head;
      temp = temp.next;
      head = head.next;
    } else {
      flag.next = head;
      flag = flag.next;
      head = head.next;
    }
  }
  temp.next = null;
  flag.next = null;

  var carry = small;
  while (carry.next != null) {
    carry = carry.next;
  }
  carry.next = big.next;
  return small.next;
};

var head = new ListNode(1);
var aaa = head;
head.next = new ListNode(2);
// head = head.next;
// head.next = new ListNode(3);
// head = head.next;
// head.next = new ListNode(2);
// head = head.next;
// head.next = new ListNode(5);
// head = head.next;
// head.next = new ListNode(2);

console.log(partition(aaa, 2))
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