标签:c语言 单链表 用c语言实现单链表的所有操作 增删查改
建立源文件List.cpp
#include"List.h"
int main()
{
Test();
system("pause");
return 0;
}建立头文件List.h
#ifndef __LIST_H__
#define __LIST_H__
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int DataType;
typedef struct ListNode
{
DataType data;
struct ListNode* next;
}ListNode;
//创建节点
ListNode* _BuyNode(DataType x)
{
ListNode* tmp = (ListNode*)malloc(sizeof(ListNode));
tmp->data = x;
tmp->next = NULL;
return tmp;
}
//尾插
void PushBack(ListNode* & head, DataType x)
{
//0节点 不为0节点
/*assert(head);*/
if (head == NULL)
{
head = _BuyNode(x);
head->next = NULL;
}
else
{
ListNode* newNode = _BuyNode(x);
ListNode* cur = head;
while (cur->next)
{
cur = cur->next;
}
ListNode* tail = cur;
tail->next = newNode;
tail = newNode;
tail->next = NULL;
}
}
//尾删
void PopBack(ListNode* & head)
{
//0节点、1节点、多节点
if (head == NULL)
{
return;
}
ListNode* cur = head;
while (cur)
{
if (cur->next == NULL) //1节点情况
{
delete cur;
cur = NULL;
head = NULL;
}
else
{
ListNode* next = cur->next;
if (next->next == NULL)
{
ListNode* tail = next;
free(tail);
tail = NULL;
tail = cur;
tail->next = NULL;
break;
}
cur = cur->next;
}
}
}
//头插
void PushFront(ListNode* & head, DataType x)
{
//0节点 1节点、多节点
if (head == NULL) //0节点
{
PushBack(head,x);
}
else
{
ListNode* cur = head;
ListNode* newNode = _BuyNode(x);
newNode->next = head;
head = newNode;
}
}
//头删
void PopFront(ListNode* & head)
{
//0节点 1节点 多节点
if (head == NULL) //0节点
{
PopBack(head);
}
else if ((head != NULL) && (head->next == NULL))
{
free(head);
head = NULL;
}
else
{
ListNode* del = head;
ListNode* cur = head->next;
head = cur;
free (del);
del = NULL;
}
}
//删除节点
void Erase(ListNode* & head, ListNode* pos)
{
assert(pos);
if (pos == head) //首节点处
{
PopFront(head);
}
else
{
ListNode* cur = head;
while (cur)
{
ListNode* next = cur->next;
ListNode* nextnext = next->next;
if (cur->next == NULL) //尾节点处
{
PopBack(cur);
break;
}
else if (next == pos) //中间节点处
{
cur->next = nextnext;
free(next);
next = NULL;
break;
}
cur = cur->next;
}
}
}
//查找节点
ListNode* Find(ListNode* & head, DataType x)
{
ListNode* cur = head;
while (cur)
{
if (cur->data == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
//打印节点
void PrintList(ListNode* & head)
{
ListNode* cur = head;
while (cur)
{
printf("%d->", cur->data);
cur = cur->next;
}
printf("NULL\n");
}
void Test()
{
ListNode* s = NULL;
PushBack(s, 1);
PushBack(s, 2);
PushBack(s, 3);
PushBack(s, 4);
PushBack(s, 5);
PrintList(s);
PopBack(s);
PrintList(s);
PushFront(s, 0);
PrintList(s);
PopFront(s);
PrintList(s);
ListNode* p = s->next;
Erase(s, p);
PrintList(s);
ListNode* ret = Find(s, 3);
printf("%d\n", ret->data);
}
#endif //__LIST_H__本文出自 “C语言100-200素数” 博客,请务必保留此出处http://10740184.blog.51cto.com/10730184/1747913
标签:c语言 单链表 用c语言实现单链表的所有操作 增删查改
原文地址:http://10740184.blog.51cto.com/10730184/1747913