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 }
  • 相关阅读:
    [Linux]
    [.Net]
    [.Net]
    [Linux]
    [Google]
    面向对象的7个基本设计原则
    windows SDK中的wininet写http客户端
    C++ 用libcurl库进行http通讯网络编程
    感悟
    关于Windows高DPI的一些简单总结
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4484464.html
Copyright © 2011-2022 走看看