如何在链表中插入? [英] How do I do insertion in linkedlist?

查看:106
本文介绍了如何在链表中插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<pre>
#include<stdio.h>
#include<stdlib.h>

struct node {
    int data;
    struct node *next;
};

struct node *createNode(){
    struct node *ptr,*head;
    ptr= (struct node *)malloc(sizeof(struct node));
    ptr->next = NULL;
}

struct node *input(){
    int num;
    struct node *p,*head,*temp;
    for(int i=0;i<5;i++){
		scanf("%d",&num);
        temp=createNode();
        temp->data=num;
    
    if(head == NULL){
        p=head=temp;
    }
    
    else{
        p=temp;
     }
    }
    return head;
}

struct node *insertNode(int value){
    struct node *p,*head,*neww;
    neww = createNode();
    neww ->data=value;
    
    if(head==NULL){
        head = neww;
    }
    else{
        while(p!=NULL){
            p->next=p;
            p = neww;
        }
    }
}

void display(struct node * head){
  struct node * ptr=head;
  while(ptr!=NULL){
    printf("%d ",ptr->data);
    ptr=ptr->next;
  }
}

void main(){
     struct node * head = input();
     insertNode(3);
     display(head);
}





我的尝试:



我写了这段代码,这有什么问题?



What I have tried:

I have written this code ,what is wrong with this?

推荐答案

它有很多错误。



您可以在网上找到关于链表的多个教程和示例。我建议先看一下。



你的代码的主要问题是你必须明白变量,并且一旦初始化就不会改变。因此,它必须是全局变量或本地实例,必须在创建后传递给每个函数。你已经为你的 display()这个功能做了这个,但是对其他人没有。



你的代码也没有正确处理新节点的插入。在那里,您必须将上一个节点的 next 成员设置为新创建的节点。执行插入(不是追加)时,还必须将新节点的 next 成员设置为上一个节点中设置的成员。因此,您必须将前一个节点传递给插入函数或头部。通过头部时,您可以在顶部插入(在头部后面)或单步执行列表以找到最后一个节点并追加。
There is a lot wrong with it.

You can find multiple tutorials and examples in the net about linked lists. I suggest to have a look at some first.

The main problem with your code is that you have to understand that the head variable is required by nearly all operations and does not change once it has been initialised. So it has to be a global variable or a local instance that must be passed to each function once it has been created. You have done this for your display() function but not for the others.

Your code is also not handling insertion of new nodes properly. There you have to set the next member of the previous node to your newly created node. When performing an insert (not an append), you must also set the next member of the new node to the one that was set in the previous one. So you have to pass either the previous node to your insert function or the head. When passing the head you can insert on top (just behind head) or step through the list to locate the last node and append.


这篇关于如何在链表中插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆