zoukankan      html  css  js  c++  java
  • LeetCode 206 Reverse a singly linked list.

    Reverse a singly linked list.

    Hint:

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

     递归的办法:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head==null) return null;
            
            if(head.next==null)return head;
            
            ListNode p=head.next;
            ListNode n=reverseList(p);
            
            head.next=null;
            p.next=head;
            return n;
        }
    }

    非递归,迭代的办法:

    if(head == null || head.next == null)
         return head; 
    ListNode current =  head.next;
    head.next = null;
    while(current ! = null){
         ListNode temp = current.next;
         current.next = head;
         head = current;
        current = temp.next;
    }
    return head;
  • 相关阅读:
    第十周作业
    第九周作业
    软件工程作业2
    自我介绍
    2019学习总结
    第二周作业
    十二周
    十一周
    第十周作业
    第九周作业
  • 原文地址:https://www.cnblogs.com/blackiesong/p/6182335.html
Copyright © 2011-2022 走看看