在第一个位置插入元素时返回的链表不正确



我是一名初学者,正在练习在链接列表中已经存在多个元素时在第一个位置插入节点的程序。这是我的代码片段

class LinkedList{
int data;
LinkedList next;
void insertNodeAtTheEnd(int d, LinkedList head){
LinkedList temp;
temp = head;
while(temp.next != null){
temp = temp.next;
}
LinkedList newNode = new LinkedList();
newNode.data = d;
newNode.next = null;
temp.next = newNode;
}
void insertNodeAtGivenPosition(int d , int pos , LinkedList head){
LinkedList temp;
temp = head;
int tempPos = 1;
LinkedList newNode = new LinkedList();
LinkedList before = temp;
if(pos == 1){
newNode.data = d;
newNode.next = temp;
temp = newNode;     
}
else { 
while(temp != null){
if(pos == tempPos){
newNode.data = d;
newNode.next = before.next ;
before.next = newNode;
}
before = temp ;
temp = temp.next ;
tempPos++;
}   
}   
}
void printLinked(LinkedList head){
LinkedList temp = head;
while(temp.next != null){
System.out.print(temp.data + "->");
temp = temp.next;
}
System.out.print(temp.data +"n");
}
}
class LinkedListMain{
public static void main(String[] args){
LinkedList node1 = new LinkedList();
node1.data = 10;
node1.next = null;
LinkedList head;
head = node1;
head.insertNodeAtTheEnd(8, head);
head.insertNodeAtTheEnd(6, head);
head.insertNodeAtTheEnd(7, head);
head.insertNodeAtTheEnd(11, head);
head.insertNodeAtTheEnd(5, head);
head.insertNodeAtTheEnd(2, head);
head.printLinked(head);
head.insertNodeAtGivenPosition(4 , 3 , head);  //line 1
head.printLinked(head);
head.insertNodeAtGivenPosition(1 , 1 , head);  //line2
head.printLinked(head);             
}
}

对于上面的代码,使用方法"insertNodeAtGivenPosition(("在第三个位置(第1行(插入元素后,代码运行良好,输出如所示

10->8->6->7->11->5->2
10->8->4->6->7->11->5->2

但当我尝试使用相同的逻辑在第一个位置(第2行(插入元素并打印列表时,第一个元素没有插入,输出看起来像

10->8->6->7->11->5->2
10->8->4->6->7->11->5->2
10->8->4->6->7->11->5->2

我做错了什么?"头"的价值似乎存在一些问题。

为了在开头插入,您必须更改head以引用新节点。但是,head被传递给您的方法,而您的方法无法更改它

为了使其工作,您需要返回新的head:

LinkedList insertNodeAtGivenPosition(int d , int pos , LinkedList head){
LinkedList temp;
temp = head;
int tempPos = 1;
LinkedList newNode = new LinkedList();
LinkedList before = temp;
if(pos == 1) {
newNode.data = d;
newNode.next = head;
head = newNode;     
} else { 
while(temp != null){
if(pos == tempPos){
newNode.data = d;
newNode.next = before.next;
before.next = newNode;
}
before = temp;
temp = temp.next;
tempPos++;
}   
}   
return head;
}

方法调用应该是:

head = head.insertNodeAtGivenPosition(1 , 1 , head);

当然,您不需要head参数,因为它是一个实例方法,所以您可以将其更改为:

LinkedList insertNodeAtGivenPosition(int d , int pos) {
LinkedList head = this;
LinkedList temp = head;
int tempPos = 1;
LinkedList newNode = new LinkedList();
LinkedList before = temp;
if(pos == 1){
newNode.data = d;
newNode.next = head;
head = newNode;     
} else { 
while(temp != null) {
if(pos == tempPos){
newNode.data = d;
newNode.next = before.next ;
before.next = newNode;
}
before = temp ;
temp = temp.next ;
tempPos++;
}   
}   
return head;
}

并称之为:

head = head.insertNodeAtGivenPosition(1 , 1);

相关内容

  • 没有找到相关文章

最新更新