• 反转链表


    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 }
  • 相关阅读:
    ServU使用方法及应用技巧
    Mozilla公布火狐4详情:更快 更支持开放标准
    FastReport4.6程序员手册_翻译 转
    Delphi调用C写的dll
    动态创建Fastreport
    字符串通用类
    去除全角半角字符
    系统运行的命令集锦
    打印机的大小设置
    旋转字体的设置
  • 原文地址:https://www.cnblogs.com/duanguyuan/p/5679885.html
Copyright © 2020-2023  润新知