查看: 1403| 回复: 1
跳转到指定楼层
上一主题 下一主题
收起左侧

[CareerCup] 我的这段很简单的反转链表哪里错了?

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 TonyJang 于 2014-9-21 11:48 编辑
  1. package chapter2;
  2. import java.util.*;
  3. public class reverseLinkedList {
  4.    
  5.    
  6.     public static<T> void reverse (ListNode<T> head){
  7.         
  8.         if(head==null||head.next==null) return;
  9.         
  10.         Stack<ListNode<T>> stack= new Stack<ListNode<T>>();
  11.         ListNode<T> cur=head;
  12.         while(cur!=null){
  13.             
  14.             stack.push(cur);
  15.             cur=cur.next;
  16.             
  17.         }
  18.         
  19.         ListNode<T> rev=stack.pop();
  20.         ListNode<T> cur2=rev;
  21.         while(!stack.empty()){
  22.             ListNode<T> next=stack.pop();
  23.             next.next=null;
  24.             cur2.next=next;
  25.             cur2=next;
  26.             
  27.             
  28.         }
  29. while(head!=null){
  30.             
  31.             System.out.print(head.data+"->");
  32.             head=head.next;
  33.             
  34.         }
  35.         
  36. while(rev!=null){
  37.    
  38.     System.out.print(rev.data+"->");
  39.     rev=rev.next;
  40.    
  41. }
  42.    
  43.     }

  44.    
  45.     public static void main(String[] args){
  46.         ListNode<Integer> Node1=new ListNode<Integer>(0);
  47.         ListNode<Integer> Node2=new ListNode<Integer>(1);
  48.         ListNode<Integer> Node3=new ListNode<Integer>(2);
  49.         ListNode<Integer> Node4=new ListNode<Integer>(1);
  50.         ListNode<Integer> Node5=new ListNode<Integer>(4);
  51.         Node1.next=Node2;
  52.         Node2.next=Node3;
  53.         Node3.next=Node4;
  54.         Node4.next=Node5;
  55.         
  56.         reverse(Node1);
  57.         
  58.         
  59.         
  60.         
  61.         
  62.         
  63.         
  64.     }
  65. }

复制代码

上一篇:CtCI和leetcode应该先刷哪一个?
下一篇:链表去重,我自己写的极简版,有点小问题
🔗
christy.zhang 2014-9-22 12:32:21 | 只看该作者
全局:
没看出来啊~ lz run的结果有问题?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表