zoukankan      html  css  js  c++  java
  • leetcode day7

    这道题弄的心好累。。

     【Reverse Linked List】206

    描述:

    Reverse a singly linked list.

    click to show more hints.

    Hint:

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    思路:

    增加一个全局节点newHead,用来指向新的头部,用用一个临时节点next来遍历整个链表,用来当旧的头部head,例如链表1-2-3-4,第一遍循环,newhead指向1,指向null,head是2,指向剩余的链表,2-3-4,然后第二遍循环,newhead指向2-1,head指向剩余的链表,3-4。。。以此类推,直到循环结束。

    // iterative solution
    
    public ListNode reverseList(ListNode head) {
        ListNode newHead = null;
        while(head != null){
            ListNode next = head.next;
            head.next = newHead;
            newHead = head;
            head = next;
        }
        return newHead;
    }

    还有递归的算法:

    // recursive solution
    public ListNode reverseList(ListNode head) {
        return reverseListInt(head, null);
    }
    
    public ListNode reverseListInt(ListNode head, ListNode newHead) {
        if(head == null)
            return newHead;
        ListNode next = head.next;
        head.next = newHead;
        return reverseListInt(next, head);
    }
  • 相关阅读:
    C# winform 数据库链接
    Second easyui框架学习
    First,映射数据库到项目
    Mybatis随笔
    spring注解简单了解
    SSH Mybatis 框架
    Maven pom.xml
    Spring
    LayaBox 摄像机Unit8Array数据获取、截图
    lvs和keepalived搭建高可用性系统
  • 原文地址:https://www.cnblogs.com/lucky-star-star/p/5003636.html
Copyright © 2011-2022 走看看