2016-04-08 81 views
1

我是编程初学者。我试图在java中实现链表我试图写函数来插入第n个位置的元素,但它不能正常工作,它没有显示数据之前的位置。这可能看起来愚蠢的问题或错误,但作为我的初学者,所以你的答案将是有益的,它将不胜感激。如何在链表中的第n个位置插入节点

谢谢先进。

该代码如下。

class Node{ 
int data; 
Node next; 
Node(){ 
    data=0; 
    next=null; 
} 
} 

class LinkedList{ 
Node head; 
LinkedList(){ 
    head=null; 
} 

    void pushB(int item){ 
     Node temp=new Node(); 
     temp.data=item; 
     temp.next=null; 
     if(head==null){ 
     head=temp;  
     } 
     else{ 
      temp.next=head; 
      head=temp; 
     } 
    } 

    void pushnth(int item, int pos){ 

    Node cur=new Node(); 
    cur.data=item; 
    cur.next=null; 
    Node temp=head; 
    int i=0; 

    while(i<pos-1){ 
     temp=temp.next; 
     i++; 
    } 
    cur.next=temp; 
    head=cur; 
    } 

    void print(){ 
     if(head==null){ 
      System.out.println("List empty"); 
     } 

     else{ 
      Node temp=head; 
      while(temp!=null){ 
       System.out.println(temp.data); 
       temp=temp.next; 
      } 
     } 
    } 
} 


public class MyFirstJavaProgram { 

public static void main(String []args) { 
    System.out.println("Hello World"); 

    LinkedList l1=new LinkedList(); 

    l1.pushB(90); 
    l1.pushB(80); 
    l1.pushB(70); 
    l1.pushB(60); 
    l1.pushB(50); 
    l1.pushB(30); 
    l1.pushB(20); 
    l1.pushB(10); 
    l1.pushnth(40,4); 
    l1.print(); 
} 
} 

回答

1

pushnth方法更改列表的head,因此丢弃新元素之前的所有元素。

为了在列表中间添加元素,您必须设置2个链接。

新的节点应该指向下一个环节,你在这里做:

cur.next=temp; 

自带之前temp应该链接到新节点的节点。这是你失踪的部分。

像这样的东西应该工作:

void pushnth(int item, int pos){ 

    Node cur=new Node(); 
    cur.data=item; 
    Node temp=head; 
    int i=0; 

    while(i<pos-2){ // note that I changed the end condition 
     temp=temp.next; 
     i++; 
    } 
    // the new node is placed between temp and temp.next 
    cur.next = temp.next; 
    temp.next = cur; 
} 

注意,此代码缺少一些验证。例如,如果链接列表中的元素太少,则此代码将失败,因此应添加一些额外的检查。

+0

非常感谢你@Eran。我知道了。 – Parvez

+0

这里我们没有修改头部,但是头部如何给我们修改列表。 – Parvez

+0

@Parvez如果你想让新节点成为第一个节点(你在'pushB'中做的),你只需要修改头部。当您在中间添加一个元素时,通过更改列表中的某个节点x的x.next来修改该列表。 – Eran