#include <stdio.h>
#include <stdlib.h>
#ifndef NULL
#define NULL ((void *)0)
#endif
typedef struct node
{
int data;
struct node *p_next;
}node;
//新建链表
node *create()
{
node * head;
head = (node *)malloc(sizeof(node));
if(!head) return NULL;
head->p_next = NULL;
return head;
}
//插入数据 链表内数据自动排序
node * insert(node *p_head,int data)
{
node * nd ;
node * p1 ;
if(!p_head) return NULL ;
nd = (node *)malloc(sizeof(node)) ;
if(!nd) return NULL ;
p1 = p_head;
while(p1 && p1->p_next && p1->p_next -> data > data )
p1 = p1 ->p_next;
nd->data = data;
nd ->p_next = p1->p_next ;
p1 ->p_next = nd ;
return p_head;
}
//打印节点信息
void print_node(node *p_head)
{
printf("0x%x -> {%d,0x%x}\n",p_head,p_head->data,p_head->p_next);
}
//打印链表
void print_list(node *p_head)
{
if(!p_head)
{
printf("List is empty .\n",p_head,length(p_head));
return ;
}
printf("List at : 0x%x,length : %d\n",p_head,length(p_head));
p_head = p_head ->p_next ;
while(p_head)
{
print_node(p_head);
p_head = p_head ->p_next;
}
}
//倒置链表
node *reverse(node *p_head)
{
node *p1,*p2,*p3;
if(!p_head ||!(p_head->p_next))
return p_head;
p1 = p_head ;
p2 = p_head->p_next;
while(p2)
{
p3 = p2->p_next;
p2->p_next = p1;
p1 = p2;
p2 = p3 ;
}
p_head->p_next = NULL ;
p_head = p1;
return p_head;
}
//查找节点
node *find_node(node *p_head,int data)
{
if(!p_head)
return NULL;
while(p_head ->p_next && p_head ->p_next ->data != data)
p_head = p_head -> p_next ;
return p_head ;
}
//删除链表
void del_list(node *p_head)
{
node *p_next;
if(!p_head)
return ;
do
{
p_next = p_head ->p_next;
p_head ->p_next = NULL ;
free(p_head);
p_head = p_next;
}while(p_head);
}
//删除节点
node *del_node(node *p_head,int data)
{
node *pn = find_node(p_head,data);
if(!pn || !(pn->p_next))
return NULL;
pn->p_next = pn->p_next->p_next;
free(pn->p_next);
return p_head ;
}
//测试长度
int length(node *p_head)
{
int k = 0;
while(p_head)
{
p_head = p_head ->p_next;
k++;
}
return k>0?(k-1) : 0 ;
}
//获取中间节点
node * mid(node *p_head)
{
node *p1,*p2;
p2 = p1 = p_head ;
while(p2)
{
p1 = (p1->p_next) ? (p1->p_next) : p1 ;
p2 = (p2->p_next) ? (p2->p_next ->p_next) : NULL ;
}
return p1;
}
int main()
{
node *pn;
node * list = create();
if(!list)
return 1;
printf("Insert several values into the list.\n");
insert(list,20);
insert(list,8);
insert(list,223);
insert(list,21);
print_list(list);
printf("Reverse the list.\n");
list = reverse(list);
print_list(list);
printf("Reverse the list again ^_^ .\n");
list = reverse(list);
print_list(list);
printf("Get the middle node ^_^ .\n");
pn = mid(list);
if(pn)
print_node(pn);
printf("Delete node with value 20 .\n");
del_node(list,20);
print_list(list);
printf("Empty the list.\n");
del_list(list);
print_list(list);
getc(stdin);
return 0;
}
最基本的单向链表操作 C语言
最新推荐文章于 2024-02-27 17:53:45 发布