#include<stdio.h>
#include<stdlib.h>
#define OK true
#define ERROR false
#define Status bool
#define OVERFLOW -2
typedef struct student{
char name[20];
int age;
}student;
typedef struct LNode{
student data;
LNode *next;
}LNode,*LinkedList;
//带头结点的单链表初始化头结点的方法
Status initLinkedList(LinkedList &L){
L = new LNode;
L->next = NULL;
return OK;
}
//带头结点的单链表销毁的方法
Status DestoryLinkedList(LinkedList &L){
LinkedList p;
while(L){
p = L;
L = L->next;
delete p;
}
return OK;
}
//带头结点的单链表清空链表的方法
Status ClearLinkedList(LinkedList &L){
LinkedList p,q;
p = L->next;
while(p){
q = p;
p = p->next;
delete q;
}
L->next = NULL;
return OK;
}
//获取单链表的长度
int GetLinkedListLength(LinkedList &L){
LinkedList p = L->next;
int count = 0;
while(p){
p = p->next;
if(!p){
count++;
}
}
return count;
}
//获取指定位置的某个元素
Status GetElem(LinkedList L,int i,student &s){
LinkedList p = L->next;
if(i < 1 || i > GetLinkedListLength(L)){
return ERROR;
}
if(!p){
return ERROR;
}
for(int i=0;i<=i-1;i++){
p = p->next;
}
s = p->data;
return OK;
}
//获取指定位置元素,课本上的实现方式
Status GetElem02(LinkedList L,int i,student &s){
LinkedList p = L->next;
int j = 1;
while(p && j < i){
p = p ->next;
j++;
}
if(!p || j>i){
return ERROR;
}
s = p->data;
return OK;
}
int GetLocation(LinkedList L,student s){
LinkedList p = L->next;
int count = 1;
while(p){
p = p->next;
if(!p){
break;
}
count++;
if(p->data.name == s.name){
return count;
}
}
return ERROR;
}
int GetLocation02(LinkedList L,student s){
LinkedList p = L->next;
int count = 0;
while(p && p->data.name != s.name){
p = p->next;
count++;
}
if(p){
return count;
}
return ERROR;
}
//插入操作
Status InsertElem(LinkedList &L,student s,int location){
LinkedList p = L;
int j = 0;
while(p && j < location-1){
p = p->next;
j++;
}
if(!p || j > location-1){
return ERROR;
}
LNode *temp = new LNode;
temp->data =s;
temp->next = p->next;
p->next = temp;
return OK;
}
Status DeleteElem(LinkedList &L,int location,student &s){
LinkedList p = L;
if(!p || location < 1 || location > GetLinkedListLength(L)){
//TODO
return ERROR;
}
int j=0;
while(p->next && j < location-1){
p = p->next;
++j;
}
if(!p->next || j>location-1){
return ERROR;
}
// for(int i=0;i < location-2;i++){
// p = p->next;
// }
LinkedList q = p->next;
s = q->data;
p->next = p->next->next;
delete q;
return OK;
}
Status AddElem(LinkedList &L,student s){
LinkedList temp = new LNode;
temp->data = s;
temp->next = L->next;
L->next = temp;
return OK;
}
Status AddElem02(LinkedList &L,student s){
LinkedList temp = new LNode;
temp->data = s;
LinkedList p = L;
while(p->next){
//TODO
p = p->next;
}
p->next = temp;
return OK;
}
void print(LinkedList L){
LinkedList p = L->next;
while(p){
printf("姓名:%s,年龄:%d\n",p->data.name,p->data.age);
p = p->next;
}
}
int main(){
LinkedList head;
initLinkedList(head);
student s1 = {"122",12};
AddElem02(head,s1);
student s2 = {"123",13};
AddElem02(head,s2);
student s3;
GetElem02(head,1,s3);
printf("%s\n",s3.name);
print(head);
}
C/C++语言实现数据结构系列(七)——单链表实现
最新推荐文章于 2023-03-16 21:29:55 发布