线性表(链式存储)—单链表
严老师书上代码问题说明:双链表部分
s->next = p->next;
p->next->prior = s;
s->prior = p;
p->next = s;
/*
需要注意这部分的双链表插入代码,包括删除代码
当所插入元素p为表尾元素时,p->next->prior 显然会出现空指针
因为p已经是最后一个元素,不存在后继何来前驱
当然这个代码如果运用到循环双链表则没有这个问题
*/
需要注意这部分的双链表插入代码,包括删除代码
当所插入元素p为表尾元素时,p->next->prior 显然会出现空指针
因为p已经是最后一个元素,不存在后继何来前驱
当然这个代码如果运用到循环双链表则没有这个问题
#include <stdlib.h>
#include <stdio.h>
using namespace std;
// element data type
typedef int ElemType;
typedef struct LNode{
ElemType data; //data
struct LNode *next; //next point
}LNode, *LinkList;
/*
LNode use to define a node
LinkList use to define a Linked List
point: LNode *p <====> LinkList L
*/
// initialize Linked List
// true----init success false-----init error, insufficient stroage space
bool initList(LinkList &L){
L = (LNode *) malloc(sizeof(LNode)); // head node initialize
if(L == NULL){
// node init error
return false;
}
L->next = NULL;
return true;
}
// destory list
bool destoryList(LinkList &L){
LNode *p = L->next;
LNode *q;
while(p != NULL){
q = p;
free(q);
p = p->next;
}
free(L);
return true;
}
// insert node in a node rear
bool InsertNextNode(LNode *p, ElemType e){
if(p == NULL){
return false;
}
LNode *s = (LNode *)malloc(sizeof(LNode));
if(s == NULL){
return false;
}
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
// insert node in a node prior
bool InsertPriorNode(LNode *p, ElemType e){
if(p == NULL){
return false;
}
LNode *s = (LNode *)malloc(sizeof(LNode));
if(s == NULL){
return false;
}
s->next = p->next;
p->next = s;
s->data = p->data;
p->data = e;
return true;
}
/*
realize node insert into a node prior by data transfer
*/
bool deleteNode(LNode *p){
if(p == NULL){
return false;
}
LNode *q = p->next;
p->next = q->next;
p->data = q->data;
free(q);
return true;
}
/*
realization procedure like over method InsertPriorNode
*/
LNode * GetElem(LinkList L, int i){
if(i < 0){
return NULL;
}
LNode *p = L; //mark point node;
int j = 0;
while(p != NULL && j < i){
p = p->next;
j++;
}
return p;
}
// insert node in i index:
/*
1. find i-1 node
2. use InsertNextNode insert node
3. return status
*/
bool ListInsertByNum(LinkList &L, int i, ElemType e){
if(i < 1){
return false;
}
LNode *p = GetElem(L,i-1);
if(p == NULL){
return false;
}
if(InsertNextNode(p,e)){
return true;
}
return false;
}
bool ListDeleteByNum(LinkList &L, int i){
if(i < 1){
return false;
}
LNode *p = GetElem(L,i);
if(p == NULL){
return false;
}
if(deleteNode(p)){
return true;
}
return false;
}
bool List_headCreate(LinkList &L){
if(L == NULL){
return false;
}
ElemType e;
scanf("%d",&e);
while(e != 9999){
if(!InsertNextNode(L,e)){
return false;
}
scanf("%d",&e);
}
return true;
}
// Traverse list and print
void printLinkList(LinkList L){
if(L == NULL){
return;
}
LNode *p = L->next;
while(p != NULL){
printf("%d",p->data);
p = p->next;
}
return;
}