最近在学习单向链表的实现,自己手敲了一段实现代码,记录一下
#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;
}
输出结果: