码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithm] Reverse a linked list

时间:2019-03-22 00:32:06      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:top   wap   val   ast   reverse   ons   UNC   ret   let   

It helps to understands how recursive calls works.

function Node(val) {
  return {
    val,
    next: null
  };
}

function LinkedList() {
  return {
    head: null,
    tail: null,
    add(val) {
      const node = new Node(val);
      if (!this.head) {
        this.head = node;
        this.tail = node;
        return node;
      }

      this.tail.next = node;
      this.tail = node;
      return node;
    },
    // 1 - -2 -- x-- x
    reverse() {
      const helper = node => {
        if (!node.next) {
          this.head = node;
          return;
        }
        helper(node.next);
        // after helper call ends
        // node is three
        // node.next is four
        // swap thre and four and point three next to null
        let temp = node.next;
        temp.next = node;
        node.next = null;
      };

      return helper(this.head);
    }
  };
}

const l = new LinkedList();

l.add("one");
l.add("two");
l.add("three");
l.add("four");
l.reverse();
console.log(l.head)
// {"val":"four","next":{"val":"three","next":{"val":"two","next":{"val":"one","next":null}}}} 

 

So for our ‘helper‘ function, when calling it, it stop there until when reach the end. 

one     |

two     |

three  |

four    |

          v

helper()

four    |

three  |

tow     |

one    v

 

To reverse the linked list, everytime we just swap last two node, then set node.next = null

[Algorithm] Reverse a linked list

标签:top   wap   val   ast   reverse   ons   UNC   ret   let   

原文地址:https://www.cnblogs.com/Answer1215/p/10575678.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!