定义结构体
typedef struct node
{
int data;
struct node *next;
} Node, *Linklist;
初始化链表
Linklist InitList()
{
Linklist head = (Node *)malloc(sizeof(Node));
head->next = NULL;
return head;
}
尾插法
void CreatTail(Linklist head)
{
Node *r, *newNode;
r = head;
int data;
scanf("%d", &data);
while (data != -1)
{
newNode = (Linklist)malloc(sizeof(Node));
newNode->data = data;
newNode->next = r->next;
r->next = newNode;
r = newNode;
scanf("%d", &data);
}
r->next = NULL;
}
头插法
void CreatHead(Linklist head)
{
Node *newNode;
int data;
scanf("%d", &data);
while (data != -1)
{
newNode = (Linklist)malloc(sizeof(Node));
newNode->data = data;
newNode->next = head->next;
head->next = newNode;
scanf("%d", &data);
}
}
链表的打印
void print(Linklist head)
{
Node *p;
p = head->next;
while (p)
{
printf(" %d\t ", p->data);
p = p->next;
}
}
链表的查找
Linklist FindNode(Linklist head, int x)
{
Node *p = head;
while (p && x >= 1)
{
p = p->next;
x--;
}
if (!p)
{
printf("该节点不存在");
return NULL;
}
else
{
return p;
}
}
链表的插入
void Insert(Linklist head, int x, int data)
{
Node *pre = FindNode(head, x - 1);
if (pre == NULL)
{
printf("请输入正确的插入点");
}
Node *pNew = (Node *)malloc(sizeof(Node));
pNew->data = data;
pNew->next = pre->next;
pre->next = pNew;
}
链表的删除
void Delete(Linklist head, int x)
{
Node *pre = FindNode(head, 0);
Node *q = pre->next;
pre->next = q->next;
free(q);
}
链表的销毁
void DestoryList(Linklist head){
Node *p = head->next;
Node *q=p;
while (p)
{
p = p->next;
free(q);
q = p;
}
head->next = NULL;
}