#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct stData{
int e;
}Data;
typedef struct stLink{
Data data;
struct stLink* next;
}Link;
struct Link* create(){
Link* head = (Link*)malloc(sizeof(Link));
memset(&head->data,0,sizeof(Link));
head->next = NULL;
return head;
}
void head_insert(Link* head,Data e){
Link *pTemp,*pNew;
if (head->data.e != 0){
pTemp = head->next;
pNew = (Link*)malloc(sizeof(Link));
memcpy(&pNew->data,&e,sizeof(Data));
pNew->next = pTemp;
head->next = pNew;
}else{
memcpy(&head->data,&e,sizeof(Data));
}
}
void nial_insert(Link* head,Data e){
Link *pTemp,*pNew;
pTemp = head;
if (head->data.e != 0){
pNew = (Link*)malloc(sizeof(Link));
memcpy(&pNew->data,&e,sizeof(Data));
while(pTemp->next != NULL)
pTemp = pTemp->next;
pTemp->next = pNew;
pNew->next = NULL;
}
else{
memcpy(&head->data,&e,sizeof(Data));
}
}
void dele(Link* head,Data e){
Link *pBefore = head;
Link *pTemp = head;
while(pTemp->next != NULL){
if (pTemp->data.e == e.e)
{
Link *pDel = pTemp;
pBefore->next = pTemp->next;
pDel->next = NULL;
free(pDel);
return;
}else{
pBefore = pTemp;
pTemp = pTemp->next;
}
}
if (pTemp->data.e == e.e)
{
Link *pDel = pTemp;
pBefore->next = pTemp->next;
pDel->next = NULL;
free(pDel);
}
}
void show(Link* head){
Link *pTemp = head;
while(pTemp->next != NULL){
printf("%d \n",pTemp->data.e);
pTemp = pTemp->next;
}
printf("%d \n",pTemp->data.e);
}
int main()
{
Link *head = create();
Data e1={1001},e2={1002},e3={1003},e4={1004};
//head_insert(head,e1);
//head_insert(head,e2);
//head_insert(head,e3);
//head_insert(head,e4);
nial_insert(head,e1);
nial_insert(head,e2);
nial_insert(head,e3);
nial_insert(head,e4);
show(head);
printf("dele------------\n");
dele(head,e2);
show(head);
return 0;
}
c语言链表,头插法和尾插法
最新推荐文章于 2024-10-17 19:09:32 发布