#include <iostream>
using namespace std;
namespace linklist {
typedef int DataType;
typedef struct node {
DataType data;
node *next;
}LinkNode;
typedef LinkNode *LinkList;
LinkList head;
LinkNode *tail_node;//最后一个节点
void InitLink() {
//在创建链表前先初始化
head = (LinkList)malloc(sizeof(LinkNode));
memset(head, 0, sizeof(LinkNode));
tail_node = head;
}
void AddNode(LinkList head, DataType elem) {
if (!head) {
return;
}
LinkNode *new_node = (LinkNode*)malloc(sizeof(LinkNode));
if (tail_node == head) {
new_node->data = elem;
new_node->next = nullptr;
head->next = new_node;
tail_node = new_node;
} else {
new_node->data = elem;
new_node->next = nullptr;
tail_node->next = new_node;
tail_node = new_node;
}
}
int Size() {
if (!head) {
return 0;
}
int count = 0;
LinkNode *first_node = head->next;
while (nullptr != first_node) {
++count;
first_node = first_node->next;
}
return count;
}
LinkNode *GetNode(LinkList head, int pos) {
if (!head) {
return nullptr;
}
LinkNode *first_node = head->next;
int j = 1;
while (nullptr != first_node && j < pos) {
first_node = first_node->next;
++j;
}
if (j == pos) {
return first_node;
}
return nullptr;
}
void InsertList(LinkList head, int pos, DataType elem) {
if (!head) {
return;
}
LinkNode *current_node = head->next;
int j = 0;
while (nullptr != current_node && j < pos-1) {
current_node = current_node->next;
++j;
}
if (nullptr == current_node) {
cout << "插入元素失败" << endl;
} else {
LinkNode *new_node = (LinkNode*)malloc(sizeof(LinkNode));
new_node->data = elem;
new_node->next = current_node->next;
current_node->next = new_node;
}
}
void DeleteList(LinkList head, int pos) {
if (!head) {
return;
}
LinkNode *current_node = head;
int i = 0;
while (nullptr != current_node && i < pos - 1) {
current_node = current_node->next;
++i;
}
if (nullptr != current_node) {
LinkNode *delete_node = current_node->next;
current_node->next = delete_node->next;
free(delete_node);
}
}
void SortList(LinkList head) {
int size = Size();
}
}
void PrintLink() {
cout << "[";
int count = linklist::Size();
for (int index = 0; index < count; ++index) {
linklist::LinkNode *node = linklist::GetNode(linklist::head, index + 1);
if (nullptr != node) {
cout << node->data << " ";
}
}
cout << "]" << endl;
}
int main() {
linklist::InitLink();
// linklist::InsertList(linklist::head, 1, 100);
linklist::AddNode(linklist::head, 60);
linklist::AddNode(linklist::head, 30);
linklist::AddNode(linklist::head, 20);
linklist::AddNode(linklist::head, 50);
//linklist::InsertList(linklist::head, 4, 40);
//linklist::InsertList(linklist::head, 7, 40);
linklist::DeleteList(linklist::head, 1);
PrintLink();
return 0;
}
线性表链表
最新推荐文章于 2024-06-02 21:47:23 发布