今天终于把链表中线性表的一系列的操作已经弄得差不多了,理解了链表的定义,初始化,设立头节点,线性表的创建,插入,删除等一系列操作,这是我今天自己重新qiao的代码:
include
using namespace std;
typedef struct LNode{
int length;
int data;
LNode next;
}LNode,LinkedList;
void InitList(LinkedList &L){
L = new LNode;//创建头节点
L->length = 0;
L->next= NULL;
L->data = 0;
}
void CreateList(LinkedList &L,int n)//尾插法
{
L = new LNode;
L->next = NULL;
LNode *r = L;//创建一个尾指针
int taotalLength = 0;
for(int i = 0;i < n;i++){
LNode *p = new LNode;
int data;
cin>>data;
p->data = data;
p->next = NULL;
r->next = p;
r = p;
taotalLength++;
}
L->length = taotalLength;
}
void AddAtIndex(LinkedList &L,int i,int val){
if(i < 0 || i > L->length )
return;
LNode *p = L;
int j = 0;
while(p && j < i){
p = p->next;
j++;
}
if(!p||j > i)
return;
LNode *s = new LNode;
s->data = val;
s->next = p->next;
p->next = s;
L->length++;
}
void DeleteIndex(LinkedList &L,int index)
{
if(index <= 0|| index>L->length)
return;
LNode* p = L;
int j = 0;
while(p->next&& j < index - 1){
p = p->next;
j++;
}
if(!(p->next)||j > index - 1)
return;
LNode *s = p->next;
p->next = s->next;
delete s;//删除临时节点
L->length--;
}
int main(){
LinkedList L;
InitList(L);
int n;
cin>>n;
CreateList(L,n);
int a,b,c;
int N;
cin>>N;
for(int i = 0;i < N; i++){
cin>>a;
if(a==0){
cin>>b>>c;
AddAtIndex(L,b,c);
}else {
cin>>b;
DeleteIndex(L,b);
}
}
LNode *p = L->next;//有空节点,所以需要后移一位
while(p){
cout<
p = p->next;
}
printf("\n");
return 0;
}