链式栈堆C语言实现

链式栈堆

抽象数据

typedef struct snode{
	DataType data;
	struct snode *next;
}LSNode;

初始化

void StackInitiate(LSNode **head){
	*head=(LSNode *)malloc(sizeof(LSNode));
	(*head)->next=NULL;
}

判断非空

void StackNotEmpty(LSNode *head){
	if(head->next==NULL)return 0;
	else return 1;
}

入栈

void StackPush(LSNode *head,DataType x){
	LSNode *p;
	p=(LSNode *)malloc(sizeof(LSNode));
	p->data=x;
	p->next=head->next;
	head->next=p;
}

出栈

int StackPop(LSNode *head,DataType *d){
	LSNode *p=head->next;
	if(p==NULL){
		printf("栈堆已空");
		return 0;
	}
	head->next =p->next;
	*d=p->data;
	free(p);
	return 1;
}

取栈顶元素

int StackTop(LSNode *head,DataType *d){
	LSNode *p=head->next;
	if(p==NULL){
		printf("栈堆已空");
		return 0;
	}
	*d=p->data;
	return 1;
}

撤销申请空间

void Destroy(SLNode *head){
	LSNode *p,*p1;
	p=head;
	while(p!=NULL){
		p1=p;
		p=p->next;
		free(p1);
	}
}
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
链式实现线性表的C语言版本可以通过定义一个结构体来表示链表节点,结构体中包含存储的数据以及指向下一个节点的指针。具体实现如下: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct ListNode { int data; // 数据域 struct ListNode *next; // 指针域,指向下一个节点 } ListNode; // 创建链表节点 ListNode* createNode(int value) { ListNode *node = (ListNode*) malloc(sizeof(ListNode)); node->data = value; node->next = NULL; return node; } // 插入节点到链表尾部 void insert(ListNode **head, int value) { ListNode *node = createNode(value); if (*head == NULL) { *head = node; } else { ListNode *current = *head; while (current->next != NULL) { current = current->next; } current->next = node; } } // 打印链表 void printList(ListNode *head) { ListNode *current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); } int main() { ListNode *head = NULL; insert(&head, 1); insert(&head, 2); insert(&head, 3); printList(head); // 输出:1 2 3 return 0; } ``` 以上代码中,通过`createNode`函数创建一个新的节点,并返回该节点的指针。`insert`函数用于将节点插入链表的末尾,如果链表为空,则直接将该节点赋值给链表的头指针,否则找到链表的末尾节点,将其next指针指向新节点。`printList`函数用于遍历链表并打印每个节点的数据。在`main`函数中,通过调用`insert`函数将数据插入链表,然后通过调用`printList`函数打印链表的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值