//
// Created by one on 2022/4/13.
//
#include <iostream>
using namespace std;
//单链表
typedef struct LNode{
int data; //存放数据域
struct LNode *next; //指向后继节点的指针
}LNode;
//构造链表
LNode* CreateLNode(int s[],int length){
// 生成头结点
LNode *Head = (LNode*)malloc(sizeof(LNode));
LNode *p = (LNode*)malloc(sizeof(LNode));
p->next = NULL;
LNode *q = p;
if(length == 0){
Head->next = NULL;
return Head;
}
// 头结点的下一个指针指向p
Head->next = p;
p->data = s[0];
p->next = NULL;
if(length == 1){
return Head;
} else{
for (int i = 1; i < length; ++i) {
p = (LNode*)malloc(sizeof(LNode));
p->data = s[i];
p->next = NULL;
q->next = p;
q = q->next;
}
return Head;
}
}
//遍历链表
void Print(LNode *Head){
LNode *p = Head->next;
while (p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
}
//增删改查
int Add(int value,LNode *Head){
// 新增结点
LNode *L = (LNode*)malloc(sizeof(LNode));
L->data = value;
L->next = NULL;
LNode *p = Head->next;
while(p){
if(p->next==NULL){
p->next = L;
return 0;
}
p=p->next;
}
return -1;
}
int AddByValueBefore(int value,int addValue,LNode *Head){
// 新增结点
LNode *L = (LNode*)malloc(sizeof(LNode));
L->data = addValue;
L->next = NULL;
LNode *p = Head->next;
if(p->data == value){
Head->next = L;
L->next = p;
return 0;
}else{
while (p){
if(p->next->data == value){
LNode *q = p->next;
p->next = L;
L->next = q;
return 0;
}
p=p->next;
}
return -1;
}
}
int DeleteByValue(int value,LNode *Head){
LNode *p = Head->next;
if(p->data==value){
Head->next = p->next;
free(p);
return 0;
} else{
while (p){
if(p->next && p->next->data == value){
LNode *q = p->next;
p->next = q->next;
free(q);
return 0;
}
p=p->next;
}
return -1;
}
}
int UpdateByValue(int value,int NewValue,LNode *Head){
LNode *p = Head->next;
while (p){
if(p->data==value){
p->data = NewValue;
return 0;
}
p=p->next;
}
return -1;
}
int UpdateByIndex(int index,int NewValue,LNode *Head){
if(index<0)return -1;
LNode *p = Head->next;
int count = 0;
while (p){
if(count==index){
p->data = NewValue;
return 0;
}
p=p->next;
count++;
}
return -1;
}
int QueryByValue(int value,LNode *Head){
LNode *p = Head->next;
while (p){
if(p->data==value){
return 0;
}
p=p->next;
}
return -1;
}
int main(){
int s[]= {6,7,0,8};
LNode *H = CreateLNode(s,4);
Print(H);
cout<<endl;
// cout<<QueryByValue(5,H)<<endl;
// cout<<UpdateByIndex(2,3,H)<<endl;
// cout<<UpdateByValue(6,5,H)<<endl;
// cout<<DeleteByValue(6,H)<<endl;
cout<<Add(8,H)<<endl;
cout<<AddByValueBefore(8,6,H)<<endl;
Print(H);
return 0;
}
单链表的实现
最新推荐文章于 2024-05-06 15:55:02 发布