繁体   English   中英

带字符串的双链表

[英]Doubly Linked List with strings

我正在尝试通过输入字符串在C中建立一个双向链接列表,如果我是对的,我想弄清楚。 我很难解释,所以我只发布我所拥有的。 我是C语言的新手,所以请纠正我,我希望我是对的,请让我知道最好发布整个代码。

好吧,我的表情看起来像这样:

 struct node
 {


  char data[100];
  struct node *previous;  // Points to the previous node
  struct node *next;   // Points out to the next node
 }*head, *last;

这是一个要插入的函数:

 void insert_beginning(char words[100])
 {
  struct node *var, *temp;
  var=(struct node *)malloc(sizeof(struct node));
  var->data[100]=words[100];

  if (head==NULL)
  {
    head=var;
    head->previous=NULL;
    head->next=NULL;
    last=head;
  }
   else
   {
    temp=var;
    temp->previous=NULL;
    temp->next=head;
    head->previous=temp;
    head=temp;
   }
 }

这是我的主要:

 int main()
 {
char words[100];
int i;

head=NULL;

printf("Select the choice of operation on link list");
printf("\n1.) insert at begining\n2.) insert at at\n3.) insert at middle");
printf("\n4.) delete from end\n5.) reverse the link list\n6.) display list\n7.)exit");

while(1)
{
    printf("\n\n Enter the choice of operation you want to do ");
    scanf("%d",&i);

    switch(i)
    {
        case 1:
        {
            printf("Enter the value you want to insert in node ");
            scanf(" %s",&words);

            insert_beginning(words);
            display();
            break;
        }

我只想确定这三个部分是否正确。 我想念什么吗? 感谢帮助。 我希望我没有复杂化,并根据需要提出问题。

您的函数insert_beginning有问题:

  var=(struct node *)malloc(sizeof(struct node));
  var->data[100]=words[100]

通过这两行,您想复制words数组并将其放在列表的节点上:)但是您的实现是错误的,您只需复制第100个char (第一个字符开始于数组cuz的范围之外) 0,最后一个在99索引处),从words数组到节点data第100个字符。

您必须复制所有words内容,因此可以使用strncpy函数进行操作:

strncpy(var->data, words, 100);

所以你的功能看起来像这样:

 void insert_beginning(char words[100])
 {
  struct node *var, *temp;
  var=(struct node *)malloc(sizeof(struct node));
  strncpy(var->data, words, 100);

  if (head==NULL)
  {
    head=var;
    head->previous=NULL;
    head->next=NULL;
    last=head;
  }
   else
   {
    temp=var;
    temp->previous=NULL;
    temp->next=head;
    head->previous=temp;
    head=temp;
   }
 }

不要使用strcpy cuz并不是防止缓冲区溢出的安全函数,请使用strncpy

它只留给您解决主要问题,我不知道您想做什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM