zoukankan      html  css  js  c++  java
  • 双向链表的学习

    #include <stdio.h>
    #include <stdlib.h>
    
    #define SLEN (sizeof(struct STU))
    
    typedef struct STU
    {
    	int a;
    	struct STU *pre;
    	struct STU *nxt;		
    }*DListNode;
    
    /*
    	创建双向链表 
    */
    DListNode create(int a)
    {
    	DListNode head=(DListNode)malloc(SLEN);	
    	head->a=a;
    	head->pre=NULL;
    	head->nxt=NULL;
    	return head;
    } 
    
    /*
    	查找要插入的位置
    	既然查询的时间复杂度都是O(n) 
    */
    DListNode find(DListNode h,int a)
    {
    	DListNode p=h;
    	if(h==NULL)
    	{
    		printf("Error:链表不能为空
    ");
    		return NULL;
    	}
    	while(p->nxt!=NULL&&p->nxt->a!=a)
    	{
    		p=p->nxt;
    	}
    	return p;
    }
    
    /*
    	双向链表的插入 
    */
    int insertElement(DListNode h,int a)
    {
    	DListNode p;
    	DListNode temp;
    	DListNode newL;
    	if(h==NULL)
    	{
    		printf("Error:表头为空
    ");
    		return 0;
    	}
    	p=find(h,a);
    	temp=p->nxt;
    	newL=(DListNode)malloc(SLEN);
    	if(newL==NULL)
    	{
    		printf("Error:申请内存失败
    ");
    		return 0;
    	}
    	if(temp!=NULL)
    	temp->pre=newL;
    	newL->a=a;
    	newL->pre=p;
    	newL->nxt=temp;
    	p->nxt=newL;
    	return 1;
    }
    
    /*
    	循环打印出双向链表 
    */
    void printfList(DListNode h)
    {
    	DListNode p=h;
    	if(h==NULL)
    	{
    		printf("链表不能为空
    ");
    	}
    	while(p!=NULL)
    	{
    		printf("%d 
    ",p->a);
    		p=p->nxt;
    	}	
    }
    
    /*
    	删除链表元素 
    */
    int deleteElement(DListNode h,int a)
    {
    	DListNode p=find(h,a);
    	DListNode t;
    	if(p==NULL)
    	{
    		return 0;
    	} 
    	if(p->nxt==NULL)
    	{
    		printf("链表中无此元素
    ");
    		return 0; 
    	}
    	if(p->nxt->nxt!=NULL)
    	{
    		t=p->nxt->nxt;
    		t->pre=p;
    	}
    	else
    	{
    		t=NULL;
    	}
    	free(p->nxt);
    	p->nxt=t;
    	return 1;
    } 
    
    int main(void)
    {
    	DListNode t;
    	DListNode n=create(10);
    	insertElement(n,1);
    	insertElement(n,2);
    	insertElement(n,3);
    	insertElement(n,4);
    	insertElement(n,5);
    	deleteElement(n,5);
    	printfList(n);
    	while(n!=NULL)
    	{
    	 	t=n->nxt;
    		free(n);		
    		n=t;
    	}
    	deleteThisList(n);
    	printfList(n); 
    }
    

      

  • 相关阅读:
    zimg
    ffmpeg P016 P010 YUV444P16LE 的打印的像素值
    zimg 使用
    P010LE P016LE YUV420P10LE
    如鹏网学习笔记(八)CSS
    对dui界面 组件 hook的通杀方案
    Python 中str 与 bytes 数据结构转换
    Tensorflow 老版本的安装
    Java string和各种格式互转 string转int int转string
    电脑黑屏
  • 原文地址:https://www.cnblogs.com/achao123456/p/6344421.html
Copyright © 2011-2022 走看看