zoukankan      html  css  js  c++  java
  • Reverse Linked List

    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?

    Iteratively:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode reverseList(ListNode head) {
    11         ListNode first = null;
    12         ListNode second = head;
    13         while(second != null){
    14             ListNode tmp = second.next;
    15             second.next = first;
    16             first = second;
    17             second = tmp;
    18         }
    19         return first;
    20     }
    21 }

    recursively:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode reverseList(ListNode head) {
    11         if(head == null || head.next == null) return head;
    12         ListNode nextNode = head.next;
    13         head.next = null;
    14         ListNode newHead = reverseList(nextNode);
    15         nextNode.next = head;
    16         return newHead;
    17     }
    18 }
  • 相关阅读:
    PHP 单态设计模式
    五中常见的PHP设计模式
    PHP如何定义类及其成员属性与操作
    thinkphp 中MVC思想
    1.4 算法
    1.3 迭代器
    1.2 容器-container
    1.1 STL 概述
    2.3顺序容器-deque
    2.2 顺序容器-list
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4484464.html
Copyright © 2011-2022 走看看