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("
    ***************
    ");
    }
    

      

  • 相关阅读:
    172. Factorial Trailing Zeroes
    96. Unique Binary Search Trees
    95. Unique Binary Search Trees II
    91. Decode Ways
    LeetCode 328 奇偶链表
    LeetCode 72 编辑距离
    LeetCode 226 翻转二叉树
    LeetCode 79单词搜索
    LeetCode 198 打家劫舍
    LeetCode 504 七进制数
  • 原文地址:https://www.cnblogs.com/-slz-2/p/13166243.html
Copyright © 2011-2022 走看看