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

反转链表 II #69

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

反转链表 II #69

louzhedong opened this issue Oct 5, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第92题

反转从位置 mn 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ mn ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

思路

顺序遍历,设置临时链表存储中间反转的链表,并标记开始和结束反转的两个节点,最后将链表串联起来

解答

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

var reverseBetween = function (head, m, n) {
  var start = new ListNode();
  start.next = head;
  var result = start;
  var count = 1;
  while (count < m) {
    count  ;
    start = start.next;
  }
  var flag = start;
  start = start.next;
  var flag2 = start;
  var cursor = new ListNode();
  while (count <= n) {
    var temp = new ListNode(start.val);
    var temp1 = temp;
    if (cursor.val != undefined) {
      temp.next = cursor;
    } else {
      flag2 = temp;
    }
    cursor = temp1;
    start = start.next;
    count  ;
  }

  flag2.next = start;
  flag.next = cursor;
  return result.next;
};

var head = new ListNode(1);
var aaa = head;
head.next = new ListNode(-2);
head = head.next;
head.next = new ListNode(-5);
head = head.next;
head.next = new ListNode(0);
head = head.next;
head.next = new ListNode(-4);

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