不带头节点的相关操作

//不带头节点的单链表
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int ElemType;
typedef struct Node{
	ElemType data;
	struct Node* next;
}Node,*plist; 
//初始化
void init(plist *phead){
	*phead=NULL;
}
Node* buyNode(ElemType val)
{
	Node* pnewnode = (Node*)malloc(sizeof(Node));
	pnewnode->data = val;
	pnewnode->next = NULL;
	return pnewnode;  //第一次调用的时候就是创建首元节点 
}
//头插法 
int insertHead(plist* phead,ElemType val){
	Node* pnewnode=buyNode(val);
	pnewnode->next=(*phead);
	(*phead)=pnewnode;
	return 0;
}
//尾插法 
int insertTail(plist* ptwohead,ElemType val){
	Node* pnewnode=buyNode(val);
	Node* ptail=*ptwohead;
	if(*ptwohead==NULL){
		(*ptwohead)=pnewnode;
	} 
	while(ptail->next!=NULL){
		ptail=ptail->next;
	}
	ptail->next=pnewnode;
	return 1;
} 
void print(Node* head){
	Node* n=head;
	while(n!=NULL){
	   printf("%d ",n->data);
	   n=n->next;
	}
    printf("\n");
}
bool empty(Node* phead)
{
	return phead==NULL?true:false;
}
int deleteHead(plist* phead){
	if(empty(*phead)){
		return 0;
	}
	Node* n=*phead;
	*phead=n->next;
	free(n);
    return 1;
}
int deleteTail(plist* phead){  
    if(empty(*phead)){  
        return 0; // 链表为空,返回0表示没有删除操作  
    }  
    Node* pfront = *phead;  
    Node* pprev = NULL; // 记录链表的倒数第二个节点 
    Node* pcur = pfront;  
    // 遍历链表直到倒数第二个节点  
    while(pcur->next != NULL){  
        pprev = pcur;  
        pcur = pcur->next;  
    } 
    // 如果链表中只有一个节点,那么pprev将仍然是NULL  
    if(pprev == NULL){  
        // 链表只有一个节点,直接删除头节点并释放内存  
        free(*phead);  
        *phead = NULL;  
    } else {  
        // 链表有多个节点,删除尾节点并释放内存  
        free(pcur);  
        pprev->next = NULL; // 将倒数第二个节点的next指针设为NULL  
    }  
    return 1; // 成功删除尾节点,返回1  
}
bool destory(plist* phead){
	Node* p1=*phead;
	Node* pnext=NULL;
	while(p1!=NULL){
		pnext=p1->next;
		free(p1);
		p1=pnext;
	}
	*phead=NULL;
	return true;
}
int main() {  
    Node* head = NULL;  
    init(&head);  
    int val;
    scanf("%d",&val);
    head= buyNode(val);
    int n;
	scanf("%d",&n); //输入要插入的值 
    if(insertHead(&head,n)==0){
   	  printf("插入成功!\n");
   	  print(head);
   } 
    int m;
    scanf("%d",&m);
    if(insertTail(&head,m)==1){
    	printf("插入成功!\n");
    	print(head);
	}
	//删除头部元素
	if(deleteHead(&head)){
		printf("成功删除头部元素!\n");
		print(head);
	} 
	if(deleteTail(&head)){
		printf("成功删除尾部元素!\n");
		print(head);
	}
	if(destory(&head)){
		printf("销毁成功!\n");
	}
    return 0; 
} 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值