看了王道的2.7节关于尾插法创建单链表
完整代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
LinkList List_Tailinsrt(LinkList&L){
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode *r=L;
scanf("%d",&x);
while(x!=9999){
LNode *s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return L;
}
void display(LinkList L){
LNode *temp=L;
while(temp){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main(){
LinkList L;
List_Tailinsrt(L);
display(L);
}
关于这句话,我以为是指针s与r都要指向头节点呢。
正确的理解应该是初始化了指针s,初始化指针r并且指向了L。
进入2.8章节,看标红的重点理解一下为何这样写?
把上面的那张图的代码复现一遍
#include<stdio.h>
#include<stdlib.h>
typedef struct DNode{
int data;
struct DNode *prior,*next;
}DNode,*DLinkList;
bool InitDLinkList(DLinkList &L){
L=(DNode *)malloc(sizeof(DNode));
if(L=NULL)
return false;
L->prior=NULL;
L->next=NULL;
return true;
}
void testDLinkList(){
DLinkList L;
InitDLinkList(L);
}
bool Empty(DLinkList L){
if(L->next==NULL)
return true;
else
return false;
}
int main(){
testDLinkList();
Empty(L);
}
运行的时候发现报错
[Error] 'L' was not declared in this scope
在int main中我们没有定义这个,所以如果写的话,应该这样
途中犯了一个弱智的额错误。
#include<stdio.h>
#include<stdlib.h>
typedef struct DNode{
int data;
struct DNode *prior,*next;
}DNode,*DLinkList;
bool InitDLinkList(DLinkList &L){
L=(DNode *)malloc(sizeof(DNode));
if(L==NULL)
return false;
DNode *L1=(DNode *)malloc(sizeof(DNode));
L->prior=NULL;
L->next=L1;
L1->data=1;
L1->prior=L;
L1->next=NULL;
return true;
}
bool Empty(DLinkList L){
if(L->next==NULL)
// printf("")
return true;
else
return false;
}
bool InsertNextDNode(DNode *p,DNode *s){
// s->prior=p->next->prior;//犯了一弱智的错误
s->prior=p;
s->next=p->next;
if(p->next!=NULL)
p->next->prior=s;
p->next=s;
}
void display(DLinkList L){
DNode *temp=L;
while(temp){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
void testDLinkList(){
DLinkList L;
InitDLinkList(L);
printf("%s","hhhhh\n");
display(L);
printf("%d",(Empty(L)));
DNode *addLNode=(DNode *)malloc(sizeof(DNode));
addLNode->data=2;
addLNode->next=NULL;
addLNode->prior=NULL;
InsertNextDNode(L->next,addLNode);
display(L);
}
int main(){
testDLinkList();
}