1.代码
注 :LinkNode,LNode 是结构类型 ;结构体指针:指向结构体类型的指针,用LinkList指针创建时,Node a用a->data来表示数据;结构体数组:数组里面存放的是结构体。malloc函数也可以包含于<stdlib.h>中。
#include <stdio.h>
#include <malloc.h>
typedef struct LinkNode{
char data;
struct LinkNode *next;
}LNode, *LinkList, *NodePtr;
链表初始化
注 :函数前LinkList表示返回值是指向LNode的一个指针类型;malloc函数返回的实际是一个无类型指针,要加上指针类型强制转换。也可以定义成LNode *p。
LinkList initLinkList (){
NodePtr tempheader = (NodePtr)malloc(sizeof(LNode));
tempheader->data = '\0';
tempheader->next = NULL;
return tempheader;
}
输出
void printlist(LinkList paraheader){
NodePtr p = paraheader->next;
while(p!=NULL)
{
printf("%c",p->data);
p=p->next;
}
printf("\n");
}
在链表后加入元素
void appendelement(LinkList paraheader,char element){
NodePtr q,p;
q =(NodePtr)malloc(sizeof(LNode));
q->data=element;
q->next=NULL;
p=paraheader;
while(p->next!=NULL)
{
p=p->next;
}
p->next=q;
}
插入
void InsertElement(NodePtr paraheader,char element,int position){
NodePtr q,p;
p=paraheader;
for(int i=0;i<position;i++)
{
p=p->next;
if(p==NULL)
{
printf("The position %d is beyond the scope of the list",position);
return;
}
}
q= (NodePtr)malloc(sizeof(LNode));
q->data=element;
printf("linking\n");
q->next=p->next;
p->next=q;
}
删除
void DeleteElement(NodePtr paraheader,char element){
NodePtr p,q;
p=paraheader;
while((p->next!=NULL)&&(p->next->data!=element)){
p=p->next;
}
if(p->next==NULL)
{
printf("Cannot delete %c\n",element);
return;
}
q=p->next;
p->next=p->next->next;
free(q);
}
注:删除中的(p->next!=NULL)与(p->next->data!=element)语句不能颠倒,&&只有当两者同时为真时才为真,当执行第一条语句为假时,计算机不会执行第二个语句。
测试
void appendlisttest(){
LinkList templist= initLinkList();
printlist(templist);
appendelement(templist,'H');
appendelement(templist,'E');
appendelement(templist,'L');
appendelement(templist,'L');
appendelement(templist,'O');
appendelement(templist,'!');
printlist(templist);
DeleteElement(templist,'e');
DeleteElement(templist,'a');
DeleteElement(templist,'!');
printlist(templist);
InsertElement(templist,'6',1);
printlist(templist);
}
void basicaddressTest(){
LNode tempNode1,tempNode2;
tempNode1.data=4;
tempNode1.next=&tempNode2;
tempNode2.data=6;
tempNode2.next=NULL;
printf("The first node: %d, %d, %d\r\n",&tempNode1, &tempNode1.data, &tempNode1.next);
printf("The second node: %d, %d, %d\r\n",&tempNode2, &tempNode2.data, &tempNode2.next);
}
int main(){
appendlisttest();
basicaddressTest();
}
2.输出
收获:通过本节课的学习,我深入了解了链表在内存中如何工作,在逻辑上又如何表达,并对链表的运用更熟练。