数据结构1.2.1单链表

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.输出

5302ca3492ce469c81be6cb45386b712.png

收获:通过本节课的学习,我深入了解了链表在内存中如何工作,在逻辑上又如何表达,并对链表的运用更熟练。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值