// doubleLink.cpp : 定义控制台应用程序的入口点。 // /* 给定一个数,从这个双向链表中删除数值为这个数的节点。如果有多个这样的节点,只要删除任意一个即可。 请给出函数原型和代码实现。 */ /* 带有头结点的双向链表,我删除的是第一个顺序遍历,发现的节点 我实在vs2008下编写的。 */ #include "stdafx.h" #include <stdlib.h> #include <stdio.h> #include <windows.h> struct node { int value; struct node *priv; struct node *next; }; /*建立一个双向链表*/ struct node* create_double_link(); /*删除指定值的双向链表*/ struct node* delete_double_link(struct node* head,int value); void print_double_link(struct node* head); struct node* create_double_link() { struct node* head=NULL; struct node* pcurrent=NULL; struct node*ptemp=NULL; int num=0,total=0; do { printf("please input the number: \n"); scanf("%d",&total); if( total == 0 ) printf("sorry,the number is error!\n"); else printf("\n"); }while( total == 0 ); while(num<total) { num=num+1; pcurrent=(struct node*)malloc(sizeof(struct node)); if( pcurrent==NULL ) { printf("malloc error,please check it!\n"); break; } else { pcurrent->value=num; } if( num == 1) { head=pcurrent; pcurrent->priv=NULL; } else { ptemp->next=pcurrent; pcurrent->priv=ptemp; } ptemp=pcurrent; } ptemp->next=NULL; return (head); } struct node* delete_double_link(struct node* head,int value) { struct node* pcurrent=NULL; pcurrent=head; if( head==NULL ) { printf("error:please check the data!\n"); return(NULL); } else { while( (value!=pcurrent->value)&&(pcurrent->next!=NULL) ) pcurrent=pcurrent->next; if(value==pcurrent->value)//find it { if( pcurrent==head )// is head node { pcurrent->next->priv=NULL; head=pcurrent->next; } else if(pcurrent->next==NULL)//wear { pcurrent->priv->next=NULL; } else { pcurrent->priv->next=pcurrent->next; pcurrent->next->priv=pcurrent->priv; } free(pcurrent); printf("the num have been deletea is: %d\n",value); } else { printf("can not find the num: %d\n",value); } } return(head); } void print_double_link(struct node* head) { struct node* ptemp; if( head == NULL) { printf("error:have no data!\n"); return; } ptemp=head; while(ptemp) { printf("num: %d\n",ptemp->value); ptemp=ptemp->next; } return; } int _tmain(int argc, _TCHAR* argv[]) { struct node* head,ptemp; int num=0; head=create_double_link(); print_double_link(head); printf("please input the delete num:\n"); scanf("%d",&num); head=delete_double_link(head, num); print_double_link(head); Sleep(10000); return 0; }
时间: 2024-11-07 20:50:37