C单向链表实现

 最近在学习单向链表的实现,自己手敲了一段实现代码,记录一下

#include <stdio.h>
#include <stdlib.h>

struct node{
	int data;
	struct node* next;
};

struct node* creatlist()
{
	struct node* headnode = (struct node*)malloc(sizeof(struct node));
	headnode->next = NULL;
	return headnode;
}

struct node* creatnode(int data)
{
	struct node* newnode = (struct node*)malloc(sizeof(struct node));
	newnode->next = NULL;
	newnode->data = data;
	return newnode;
}

//按顺序插入
void insertnode(struct node* list,int data)
{
	struct node* pmove = list->next;
	struct node* pmovefront = list;
	struct node* newnode = creatnode(data);
	
	while(pmove != NULL && pmove->data <= data) {
		pmovefront = pmove;
		pmove = pmove->next;
	}
	pmovefront->next = newnode;
	newnode->next = pmove;
		
	
}

void printlist(struct node* list)
{
	struct node* pmove = list->next;
	while(pmove != NULL)
	{
		printf("%d",pmove->data);
		pmove = pmove->next;
	}
	printf("\n");
}

void delnode(struct node* list, int data)
{
	struct node* posnode = list->next;
	struct node* posnodefront = list;
	
	if(posnode == NULL)
		printf("链表为空\n");
	else {
		while(posnode->data != data) {
			posnodefront = posnode;
			posnode = posnode->next;
			if(posnode == NULL){
				printf("找不到对应结点\n");
				return;
			}
		}
		
		posnodefront->next = posnode->next;
		free(posnode);
			
	}
}

int main()
{
	struct node *list;
	list = creatlist();
	insertnode(list,6);
	insertnode(list,4);
	insertnode(list,9);
	insertnode(list,2);
	insertnode(list,5);
	insertnode(list,7);
	insertnode(list,0);
	insertnode(list,1);
	insertnode(list,9);
	insertnode(list,8);
	insertnode(list,3);
	printlist(list);
	delnode(list, 1);
	printlist(list);
    return 0;
}

输出结果: 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值