关于向链表中添加一个节点,出现错误 求解惑
在写一个关于链表的程序,在向其中添加一个节点出现错误,下面是相关代码,至于其它关于删除和遍历的代码省略,拜托大家发现问题;
程序代码:
/*头文件, list.h*/
#ifndef _LIST_H_
#define _LIST_H_
#define MAXSIZE 30
struct classmate
{
char name[MAXSIZE];
char sex[MAXSIZE];
int age;
};
typedef struct classmate Item;
typedef struct node
{
Item item;
struct node *next;
}Node;
typedef struct list
{
Node *head;
int size;
}List;
typedef struct pair
{
Node * previous;
Node * current;
}Pair;
void InitializeList(List * plist);
int ListIsEmpty(const List *plist);
int AddItem(const Item *pitem1,const Item *pitem2,List * plist);
#endif // _LIST_H_
程序代码:
/*实现头文件功能,list.cpp*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
static Pair SeekItem(const Item *pitem,const List *list);
static Node * MakeNode(const Item *pitem);
void InitializeList(List *plist)
{
plist->head=NULL;
plist->size=0;
}
int ListIsEmpty (const List * plist)
{
if(plist->head==NULL)
return 1;
else
return 0;
}
int AddItem(const Item * pitem1,const Item *pitem2,List *plist)
{
Node * new_node;
Node * flag;
Node * temp;
flag=plist->head;
if(SeekItem(pitem1,plist).current!=NULL)
{
printf("the item has been exist.\n");
return 0;
}
new_node=MakeNode(pitem1);
if(new_node==NULL)
{
printf("failed to creat a new node.\n");
return 0;
}
plist->size++;
if(plist->head==NULL)
plist->head=new_node;
else if(pitem2->name==NULL)
{
while(flag->next!=NULL)
flag=flag->next;
flag->next=new_node;
}
else
{
temp=SeekItem(pitem2,plist).previous;
new_node->next=temp->next;
temp->next=new_node;
}
return 1;
}
static Node * MakeNode(const Item *pitem)
{
Node * new_node;
new_node=(Node *)malloc(sizeof(Node));
if(new_node!=NULL)
{
new_node->item=*pitem;
new_node->next=NULL;
}
return new_node;
}
static Pair SeekItem(const Item *pitem,const List *plist)
{
Pair temp;
temp.previous=NULL;
temp.current=plist->head;
while(strcmp(pitem->name,temp.current->item.name)==0||temp.current==NULL)
{
temp.previous=temp.current;
temp.current=temp.current->next;
}
return temp;
}
程序代码:
/*测试函数,,,listtest.cpp*/
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
void AddOne (List *plist);
int main(void)
{
List classmates;
; InitializeList(&classmates);
AddOne(&classmates);
puts("good job\n");
return 0;
}
void AddOne(List *plist)
{
Item temp,temp1;
puts("please enter your classmate\'s name:\n");
gets(temp.name);
puts("please enter sex of your classmate:\n");
gets(temp.sex);
puts("please enter age of your classmate:\n");
scanf("%d",&temp.age);
printf("请输入你所希望将该项目添加的位置之前项目的名字:(输入空行自动添加到链表结尾)。\n");
gets(temp1.name);
AddItem(&temp,&temp1,plist);
}








