[英]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.