【Leetcode】206 Reverse Linked List

来源:互联网 发布:矩阵的概念ppt 编辑:程序博客网 时间:2024/04/27 13:53

我的答案以及大神答案

我的答案:

/** * 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) {        Stack<ListNode> sk = new Stack<ListNode> ();        if(head != null){            sk.push(head);            while(head.next != null) {                head = head.next;                sk.push(head);            }            head = sk.pop();            while(!sk.isEmpty()) {            head.next = sk.pop();            }        }        else {            return null;        }        return head;    }}

空间复杂度O(n)

提交,然后。。。应该是代码写的有问题。需要再调试。

 Status:

Memory Limit Exceeded

 

大神答案:http://blog.csdn.net/xudli/article/details/45715463

 1.recursion 递归

    /**      * 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;          }      }  

2.iteration

    /**      * Definition for singly-linked list.      * public class ListNode {      *     int val;      *     ListNode next;      *     ListNode(int x) { val = x; }      * }      */              // 1 <-2 3      public class Solution {          public ListNode reverseList(ListNode head) {              if(head==null || head.next==null) return head;                            ListNode pre = head;              ListNode p = head.next;              pre.next = null;              ListNode nxt;              while(p!=null) {                  nxt = p.next;                  p.next = pre;                  pre = p;                  p = nxt;              }              return pre;          }      }  
分析:用了三个指针,每次更改中间指针的指向,向后移动一位,继续刚才的操作。

0 0