自定义一个头文件
#ifndef _LINK_
#define _LINK_
#include <stdio.h>
#include <stdlib.h>
typedef struct link
{
int date; //数据域
struct link *next; //指针域
} LINK;
extern LINK *seq_init(void); //初始化链表
extern void seq_head_insert(LINK *head, int elem); //头插
extern void seq_dispiay(LINK *head); //遍历链表
extern void seq_tail_insert(LINK *head, int elem); //尾插
extern int seq_del(LINK *head, int elem); // 删除
extern int seq_select(LINK *head, int elem); //查找
extern void seq_change(LINK *head, int oldelem, int newelem); //改数据
extern void seq_server(LINK *head); //练习
#endif
函数文件
#include "link.h"
//初始化
LINK *seq_init(void)
{
LINK *head = (LINK *)malloc(sizeof(LINK));
head->next = NULL;
return head;
}
//头插
void seq_head_insert(LINK *head, int elem)
{
LINK *node;
node = (LINK *)malloc(sizeof(LINK));
node->date = elem;
node->next = head->next;
head->next = node;
}
//遍历
void seq_dispiay(LINK *head)
{
LINK *temp;
temp = head->next;
while (temp != NULL)
{
printf("%d>>", temp->date);
temp = temp->next;
}
}
//尾插
void seq_tail_insert(LINK *head, int elem)
{
LINK *temp;
LINK *p = (LINK *)malloc(sizeof(LINK));
p->date = elem;
temp = head->next;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = p;
p->next = NULL;
}
//删除
int seq_del(LINK *head, int elem)
{
LINK *temp, *p;
temp = head;
while (temp != NULL)
{
if (temp->next->date == elem)
{
p = temp->next;
temp->next = p->next;
free(p);
return 1;
}
temp = temp->next;
}
return 0;
}
//查询某个数据的位置
int seq_select(LINK *head, int elem)
{
int i = 1;
LINK *temp;
temp = head->next;
while (temp != NULL)
{
if (temp->date == elem)
{
return i;
}
temp = temp->next;
i++;
}
return 0;
}
//修改某个数据为新数据
void seq_change(LINK *head, int oldelem, int newelem)
{
LINK *temp;
temp = head->next;
while (temp != NULL)
{
if (temp->date == oldelem)
{
temp->date = newelem;
}
temp = temp->next;
}
}
//数据逆转
// 2、用单向链表实现数据逆转,首先建立一个包含若干整数的单向链表,
//然后参考讲义的例子实现数据的逆转。(比如说把1,2,3,4,5逆转成5,4,3,2,1)
void seq_server(LINK *head)
{
LINK *newhead, *p;
p = newhead = head->next;
head->next = NULL;
while (newhead != NULL)
{
newhead = newhead->next;
seq_head_insert(head, p->date);
free(p);
p = newhead;
}
}
主函数文件
#include "link.h"
int main(void)
{
LINK *head = NULL; //初始化
head = seq_init();
int i;
for (i = 1; i <= 5; i++) //头插
{
seq_head_insert(head, i);
seq_dispiay(head);
printf("\n");
}
printf("*****************\n");
for (i = 6; i <= 10; i++) //尾插
{
seq_tail_insert(head, i);
seq_dispiay(head);
printf("\n");
}
int ret = seq_del(head, 5); //删除
if (ret)
{
printf("删除成功\n");
seq_dispiay(head);
printf("\n");
}
else
{
printf("删除失败\n");
}
int j = seq_select(head, 8); //查找
if (j)
{
printf("查找成功\n");
printf("%d的位置是%d\n", 8, j);
}
else
{
printf("查找失败\n");
}
seq_change(head, 8, 80); //修改
seq_dispiay(head);
printf("\n");
seq_server(head);
seq_dispiay(head);
printf("\n");
}