C语言 链表创建及操作
- 第一部分构建链表,定义结构体,分别用头插法、尾插法实现,这里封装了打印函数:
printf();
做练习方便后续使用;对链表进行查找,并将查找到的值构建一个新的链表;链表的转置;具体代码如下:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void print_data(struct node *inc)
{
printf("data = %d\n",inc->data);
}
void traverse(struct node *inc, void(*print)(struct node *))
{
while(inc)
{
print(inc);
inc = inc->next;
}
}
void insertHead(struct node **inc, int n)
{
struct node *tmp = malloc(sizeof(struct node));
tmp->data = n;
tmp->next = *inc;
*inc = tmp;
}
void insertTail(struct node **inc, int n)
{
struct node *tmp = malloc(sizeof(struct node));
tmp->data = n;
tmp->next = NULL;
while(*inc)
{
inc = &(*inc)->next;
}
*inc = tmp;
}
struct node *findNode(struct node **inc, int goal)
{
struct node *newlist = NULL;
struct node *tmp = *inc;
struct node *pre;
struct node *cur;
while(tmp->next)
{
if(goal == tmp->next->data)
{
pre = tmp;
cur = tmp->next;
tmp->next = cur->next;
cur->next = newlist;
newlist = cur;
}else if(goal == tmp->data){
*inc = (*inc)->next;
tmp->next = newlist;
newlist = tmp;
tmp = *inc;
}else{
tmp = tmp->next;
}
}
return newlist;
}
void transNode(struct node **inc)
{
struct node *cur = *inc;
struct node *pre = NULL;
struct ndoe *tmp;
while(*inc)
{
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
*inc = pre;
}
int main()
{
struct node *p = NULL;
insertHead(&p,10);
insertHead(&p,20);
insertHead(&p,10);
insertHead(&p,30);
insertHead(&p,10);
insertHead(&p,40);
printf("_____create list_____\n");
traverse(p,print_data);
printf("_____old list_____\n");
struct node *ret = findNode(&p, 10);
traverse(p,print_data);
printf("_____new list_____\n");
traverse(ret,print_data);
return 0;
}
- 执行结果如下: