#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
LNode *initList()
{
LNode *list = (LNode *)malloc(sizeof(LNode));
if(list == NULL)
{
return NULL;
}
list->data = 0;
list->next = NULL;
return list;
}
int headInsert(LNode *list, int data)
{
LNode *node = (LNode *)malloc(sizeof(LNode));
if(NULL == node)
{
printf("malloc new node failed\n");
return -1;
}
node->data = data;
node->next = list->next;
list->next = node;
return 0;
}
int tailInsert(LNode *list, int data)
{
// LNode *head = list;
LNode *node = (LNode *)malloc(sizeof(LNode));
if(NULL == node)
{
printf("malloc new node failed\n");
return -1;
}
node->data = data;
node->next = NULL;
list = list->next;
while (list->next)
{
list = list->next;
}
list->next = node;
return 0;
}
int deleteNode(LNode *list, int data)
{
LNode *pre = list;
LNode *cur = list->next;
while(cur)
{
if(cur->data == data)
{
pre->next = cur->next;
free(cur);
break;
}
else
{
pre = cur;
cur = cur->next;
}
}
return 0;
}
void printList(LNode *list)
{
list = list->next;
while(list)
{
printf("%d -> ", list->data);
list = list->next;
}
printf("NULL\n");
}
int main()
{
LNode *list = initList();
if(NULL == list)
{
printf("init failed\n");
return 0;
}
headInsert(list, 0);
headInsert(list, 1);
headInsert(list, 2);
headInsert(list, 3);
tailInsert(list, 4);
tailInsert(list, 5);
tailInsert(list, 6);
tailInsert(list, 7);
printList(list);
deleteNode(list, 2);
deleteNode(list, 6);
printList(list);
return 0;
}
暂无评论