#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
assert(newNode);
newNode->data = data;
newNode->next = NULL;
return newNode;
}
//无头链表有两种写法
//No.1 简单写法: 再封装法
//1.1 一个指针(表头)
//1.2 两个指针(记录表头表尾的方式)
struct List
{
struct Node* headNode; //指向链表的第一个节点,表示整个链表
struct Node* tailNode; //永远指向最后一节点
int listSize; //大多数数据结构中都有的一个属性(当前数据结构中的元素个数) 万金油参数
};
struct List* createList()
{
struct List* list = (struct List*)malloc(sizeof(struct List));
assert(list);
list->listSize = 0;
list->headNode = NULL;
list->tailNode = NULL;
return list;
}
void insertByHead(struct List* list,int data)
{
struct Node* newNode = createNode(data);
if (list->listSize == 0)
{
list->tailNode = newNode;
//list->headNode = newNode;
//list->listSize++;
}
else
{
newNode->next = list->headNode;
//list->headNode = newNode;
//list->listSize++;
}
list->headNode = newNode;
list->listSize++;
}
void insertByTail(struct List* list, int data)
{
struct Node* newNode = createNode(data);
if (list->listSize == 0)
{
list->headNode = newNode;
//list->tailNode = newNode;
//list->listSize++;
}
else
{
list->tailNode->next = newNode;
//list->tailNode = newNode;
//list->listSize++;
}
list->tailNode = newNode;
list->listSize++;
}
//指定插入: 唯一的问题是: 如果采用指定位置前面插入,要考虑表头插入
//data: 插入的数据
//posData: 插入的位置(参照点)
void insertAppoin(struct List* list, int data, int posData)
{
//对于查找,初始值赋值操作,是看你操作的时候判断是否顺利
struct Node* posLeftNode = list->headNode;
struct Node* posNode = list->headNode;
while (posNode != NULL && posNode->data != posData)
{
posLeftNode = posNode;
posNode = posLeftNode->next; //
//posNode=posNode->next;
}
if (posNode == NULL)
{
printf("无法插入!\n");
}
else if(posNode==list->headNode)
{
insertByHead(list, data);
}
else
{
struct Node* newNode = createNode(data);
posLeftNode->next = newNode;
newNode->next = posNode;
list->listSize++;
}
}
//自己写删除
//删除相对于有头链表更难
//表头删除
void deleteHead(struct List* list)
{
if (list->listSize == 0)
{
printf("无法删除!\n");
}
else
{
struct Node* nextNode = list->headNode->next; //NULL
free(list->headNode);
list->headNode = nextNode; //NULL
if (list->listSize == 1) //nextNode==NULL list->headNode==NULL
list->tailNode = NULL;
list->listSize--;
}
}
//表尾删除
//指定删除
void printList(struct List* list)
{
struct Node* pMove = list->headNode;
while (pMove != NULL)
{
printf("%d\t", pMove->data);
pMove = pMove->next;
}
printf("\n");
}
//No.2 二级指针写法
int main()
{
struct List* list = createList();
for (int i = 0; i < 3; i++) //2 1 0
{
insertByHead(list, i);
}
for (int i = 0; i < 3; i++) //2 1 0 0 1 2
{
insertByTail(list, i);
}
printList(list);
insertAppoin(list, 100, 0);
printList(list);
insertAppoin(list, 100, 2);
printList(list);
struct List* mylist = createList();
insertByHead(mylist, 1);
printList(mylist);
deleteHead(mylist);
printList(mylist);
insertByTail(mylist,2);
printList(mylist);
return 0;
}
无头链表(完整版)
最新推荐文章于 2021-09-19 15:07:52 发布