2016-11-23 53 views
-1

我面临着参考操作的问题: 首先这是一个代码,其值为x并遍历List,删除任何具有小于或等于X值的链接,但它给了我一个不规则的输出。帮助被赞赏。单链表参考操作

public void rlx (int x){ 
     Link p = head;//Initializing a pointer equal to head 
     for (Link c = head.next; c!=null;c=c.next) {//Initializing another Pointer with the Condition to termination 
      if((int)head.data<=x){//If the Value of head< = to X 
       head=head.next;//Skip the first and assign head to the second 
      }else if((int)c.data<=x){ 
       p.next=c.next;//P.next skip c by pointing to c.next instead of c; 
      } 
      p=c; reinitialize p; 
     } 

    } 

主要方法:

public static void main(String [] args){ 
    LinkList l = new LinkList(); 
    l.insertLast(1); 
    l.insertLast(2); 
    l.insertLast(3); 
    l.insertLast(4); 
    l.insertLast(3); 
    l.insertLast(2); 
    l.insertLast(1); 
    l.rlx(3); 
    System.out.print(l); 
} 

输出:[4,2]

+0

我们需要更多信息才能开始诊断正在发生的事情。从我看来,你*可能*也有数据插入的问题。 – Makoto

+0

我认为问题是数据删除,因为输出Result应该是[4],因为所有其他值都等于或小于x。我希望我可以做到这一点,而不使用其他链接列表。注意这个类是由我自己制作的,这个方法是内部的。@ Makoto –

回答

0

你的算法有很多的问题,我真的不知道从哪里开始。首先,你不应该在每次循环迭代时检查头部,你应该只检查c.data < = x。其次,只需将前一个指针指向后面的节点,就不会从单个链接列表中删除节点。如果c.data> x不是每次迭代都应该设置p = c。我一般都反对这样做的人的作业规则,但在这里

public void rlx (int x){ 
    While(head != null && (int)head.data <= x) { 
     head = head.next 
    } 
    Link p = head;//Initializing a pointer equal to head 
    for (Link c = head.next; c!=null;c=c.next) {//Initializing another Pointer with the Condition to termination 
     if((int)c.data<=x){ 
      p.next=c.next;//P.next skip c by pointing to c.next instead of c; 
     } 
     Else { 
      p=c; 
     } 
    } 
} 

我没有打扰来测试,因为它基本上是伪代码,我假设你的链接类型是一个指针对象。基本上,你需要明确地做垃圾收集,但更重要的是,你应该删除头部,直到在while循环中找到一个大于x的值,然后使用单独的for循环来删除头部之后的值。否则,如果头部小于x,c小于x,则会移除头部,然后变为c,但由于p仍然是旧头部,因此您会更新列表,以便旧头部指向下一个值是没有意义的,因为没有指向p并且你当前的头将是不大于x的c。那么,p将变成c,它不大于x。 p只应该指向最近发现的大于x的链接,并且只有在找到链接大于x的链接后才会被替换。

+0

非常感谢。 –