zoukankan      html  css  js  c++  java
  • 双链表的插入删除

    #include<stdio.h>
    #include<malloc.h>
    typedef char ElemType;
    typedef struct DNode
    {
    	ElemType data;
    	struct DNode *prior;
    	struct DNode *next;
    }DNode,*DLinkList;
    DLinkList DLinkList_Init(DLinkList &L)		//初始化双链表
    {
    	L=(DNode*)malloc(sizeof(DNode));
    	if(L==NULL)
    		return false;
    	L->prior=NULL;
    	L->next=NULL;
    	return L;
    }
    bool DLinkList_Insert(DLinkList &L,int i,ElemType e)	//双链表的插入
    {
    	if(i<0)
    		return false;
    	DNode *s,*p=L;
    	int j=0;
    	while(j	<i-1 && p!=NULL)		//找到第i-1个节点
    	{
    		p=p->next;
    		j++;
    	}
    	if(p==NULL)
    		return false;
    	s=(DNode*)malloc(sizeof(DNode));
    	s->data=e;
    	s->next=p->next;
    	if(p->next!=NULL)		//判断空指针
    		p->next->prior=s;
    	s->prior=p;
    	p->next=s;
    	return true;
    }
    bool DLinkList_Delete(DLinkList &L,int i)
    {
    	if(i<0)
    		return false;
    	DNode *p=L,*q=L->next;
    	int j=0;
    	while(j<i-1 && p!=NULL)		//找到第i-1个节点
    	{
    		p=p->next;
    		q=p->next;
    		j++;
    	}
    	if(p==NULL)
    		return false;
    	p->next=q->next;		
    	if(q->next!=NULL)		//判断空指针
    		q->next->prior=p;
    	free(q);
    	return true;
    }
    bool DLinkList_Print(DLinkList L)
    {
    	if(L==NULL)
    		return false;
    	DNode *p=L->next;
    	while(p!=NULL)
    	{
    		printf("%c	",p->data);
    		p=p->next;
    	}
    	return true;
    }
    void main()
    {
    	DNode *L;
    	DLinkList_Init(L);
    	DLinkList_Insert(L,1,'a');
    	DLinkList_Insert(L,2,'b');
    	DLinkList_Insert(L,3,'c');
    	DLinkList_Insert(L,4,'d');
    	DLinkList_Print(L);
    	printf("
    ***************
    ");
    	DLinkList_Delete(L,2);
    	DLinkList_Print(L);
    	printf("
    ***************
    ");
    }
    

      

  • 相关阅读:
    宏------进阶

    公司用中会用到的iOS开源库和第三方组件(不断更新...)
    iOS 开发者旅途中的指南针
    国际化
    Block
    git简单使用教程
    XCode自带解析SAX解析
    GDataXMLNode解析XML
    Predicate
  • 原文地址:https://www.cnblogs.com/-slz-2/p/13166243.html
Copyright © 2011-2022 走看看