反转链表

2016-07-18

来源:牛客网 http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca

反转链表一般有四种方法:

(1)借助栈,或者数组

(2)用三个指针逐个节点反转

(3)递归。

(4)从第2个节点到第N个节点,依次逐节点插入到第1个节点(head节点)之后,最后将第1个节点挪到新表的表尾

本题有内存限制,不能使用额外空间,方法(1)不行;方法(2)可行。

方法(3)仅仅写了用递归的方式打印反转的链表,没写返回一个反转链表。(4)未尝试。

 1 import java.util.Stack;
 2 
 3 /*class ListNode {
 4     int val;
 5     ListNode next = null;
 6 
 7     ListNode(int val) {
 8         this.val = val;
 9     }
10 }
11 */
12 
13 public class Solution {
14 
15     // using Statck
16     public ListNode ReverseList(ListNode head) {
17         if(head==null) return null;
18         Stack<ListNode> stack = new Stack<ListNode>();
19         stack.push(head);
20         while(head.next!=null){
21             stack.push(head.next);
22         }
23 
24         ListNode h = stack.pop();
25         ListNode node = h;
26         while(!stack.empty()){
27             node.next=stack.pop();
28         }
29         return h;
30     }
31 
32     // three pointer 
33      public ListNode ReverseList(ListNode head) {
34         if(head==null) return null;
35         if(head.next==null) return head;
36  
37         ListNode p=head,q=p.next, tmp;
38         p.next=null; // 把第1个节点的next置空,否则第1、2个节点会形成一个环
39         while(q!=null){
40             tmp=q.next;
41             q.next=p;
42 
43             p=q;
44             q=tmp;
45         }
46         return p;
47     }
48 
49     // print recursively
50     public void ReverseList(ListNode head) {
51         if(head==null) return null;
52         if(head.next!=null){
53             ReverseList(head.next);
54         }
55         System.out.print(head.val+" ");
56     }
57 
58 }
原文地址:https://www.cnblogs.com/duanguyuan/p/5679885.html