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); 
    }
    

      

  • 相关阅读:
    1063. Set Similarity
    A1047. Student List for Course
    A1039. Course List for Student
    最大公约数、素数、分数运算、超长整数计算总结
    A1024. Palindromic Number
    A1023. Have Fun with Numbers
    A1059. Prime Factors
    A1096. Consecutive Factors
    A1078. Hashing
    A1015. Reversible Primes
  • 原文地址:https://www.cnblogs.com/achao123456/p/6344421.html
Copyright © 2011-2022 走看看