美文网首页
leecode 206:将链表反转

leecode 206:将链表反转

作者: 小强不是蟑螂啊 | 来源:发表于2019-06-13 20:55 被阅读0次

题目:
反转一个单链表。

示例:

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

遍历

var reverseList = function(head) {
  if(head == null || head.next == null) return head;
  while(head.next){
 
  }  
};

递归

var reverseList = function(head) {
  if (head === null || head.next === null) {
    return head;
  }
  
  var new_head = reverseList(head.next);  // 反转后的头节点
  head.next.next = head;                  // 将反转后的链表的尾节点与当前节点相连
  head.next = null;
  return new_head;
  }

相关文章

网友评论

      本文标题:leecode 206:将链表反转

      本文链接:https://www.haomeiwen.com/subject/kspefctx.html