LinkList Operation

链表典型数据结构:

#define ElemType int
typedef struct LinkNode{
ElemType value;
struct LinkNode* next;
};

相比于顺序结构,链式存储结构好处在于在任意位置插入或者删除元素,操作时间比较短。 1 节点回收以及申请

注意指针和节点的关系,防止产生游离节点。记住不管是节点内容以及指针一定要初始化

LinkList Create_Linkist(int elem){
LinkList head;
head = (LinkList)malloc(sizeof(LinkNode));
if(!head) exit(EXIT_FAILURE);
head->value = elem;
head->next = NULL;
return head;
}

假设head指针指向第一个元素,那么插入元素时

无序插入表头插入

void Insert_Head(LinkList head, int elem){
if(!head) head = Create_Linkist(elem);
else{
LinkList temp = Create_Linkist(elem);
temp->next = head->next;
head->next = temp;
}
}

无序插入表尾插入 (q 为表尾指针)

void Insert_Tail(LinkList &head, int elem){
if(!head) head = Create_Linkist(elem);
else{
LinkList temp = head; while(temp->next) temp = temp->next;
temp->next = Create_Linkist(elem);;
}
}

有序插入操作递归实现

void InsertSorted(LinkList &head, int elem){
if(head == NULL || head->value >= elem){
LinkList temp = Create_Linkist(elem);
temp->next = head;
head = temp;
}
else InsertSorted(head->next, elem);
}

打印函数

void print(LinkList head){
while(head){
cout<<head->value<<" ";
head = head->next;
}
}

源代码:

#include <iostream>
#include <stdlib.h>
using namespace std; #define ElemType int
typedef struct LinkNode{
ElemType value;
struct LinkNode* next;
}*LinkList; LinkList Create_Linkist(int elem){
LinkList head;
head = (LinkList)malloc(sizeof(LinkNode));
if(!head) exit(EXIT_FAILURE);
head->value = elem;
head->next = NULL;
return head;
} void Insert_Head(LinkList head, int elem){
if(!head) head = Create_Linkist(elem);
else{
LinkList temp = Create_Linkist(elem);
temp->next = head->next;
head->next = temp;
}
} void Insert_Tail(LinkList &head, int elem){
if(!head) head = Create_Linkist(elem);
else{
LinkList temp = head; while(temp->next) temp = temp->next;
temp->next = Create_Linkist(elem);;
}
} void InsertSorted(LinkList &head, int elem){
if(head == NULL || head->value >= elem){
LinkList temp = Create_Linkist(elem);
temp->next = head;
head = temp;
}
else InsertSorted(head->next, elem);
} void print(LinkList head){
while(head){
cout<<head->value<<" ";
head = head->next;
}
} int main()
{
LinkList linkTest;
int testNum;
cout<<"enter test number: ";
cin>>testNum;
linkTest = Create_Linkist(testNum);
print(linkTest);
cout<<linkTest<<endl;
InsertSorted(linkTest, --testNum);
//Insert_Tail(linkTest, ++testNum);
//Insert_Head(linkTest, ++testNum);
cout<<"link after insert: "<<endl;
print(linkTest); system("pause");
return 0;}






版权声明:本文为博主原创文章,未经博主允许不得转载。

上一篇:jdk11新特性


下一篇:ArrayList 、Vector、 LinkList