[Algorithm] Reverse a linked list

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Algorithm] Reverse a linked list相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

[Algorithm] 206. Reverse Linked List

1074 reverse list

[Algorithm] Reverse String II

[Algorithm] 234. Palindrome Linked List / Reverse linked list

[LeetCode]-algorithms-Reverse Integer

leetcode557. Reverse Words in a String III