[Dev-C++] A double chain list problem about delete the special node
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <per...@ya...> - 2004-06-03 01:14:52
|
I have write a double chain list program that do only some simple operation.But the result of the function DeleteList() is not natural.It will delete all the node before the ith node.I haven't found the reason of the problem by far.Can someone can me why and how to improve it?
---Thanks,
Bruce.J
My program is list belove:
/* ************************************************************ */
#include <stdio.h>
enum bool {FALSE, TRUE};
typedef enum bool BOOL;
typedef int DATA;
typedef struct DoubleLink {
DATA data;
struct DoubleLink *prev;
struct DoubleLink *next;
} DoubleLink;
/* Input the value of n entries element to create a double chain list */
DoubleLink *CreateList(DoubleLink *p, int n)
{
DoubleLink *ptr;
int i;
p = (DoubleLink *) malloc(sizeof(DoubleLink));
/* First create a empty double chain list with a head pointer */
p->next = NULL;
p->prev = NULL;
for (i = 0; i < n; ++i) {
ptr = (DoubleLink *) malloc(sizeof(DoubleLink));
scanf("%d", &ptr->data);
ptr->prev = p;
ptr->next = p->next;
p->next = ptr;
}
return p;
}
/* Get the length of the double chain list */
int GetLength(DoubleLink *p)
{
DoubleLink *p1;
int i = 0;
p1 = p->next;
while (p1) {
++i;
p1 = p1->next;
}
return i;
}
/* Delete the ith element */
/* It has a problem that it will delete the all element which before the ith element when I run it,but I don't know why.*/
BOOL DeleteList(DoubleLink *p, int i)
{
if (i<1 || i>GetLength(p))
return FALSE;
DoubleLink *p1;
int j = 0;
p1 = p;
while(p1 && j<i) {
p1 = p1->next;
++j;
}
if (p1->next == NULL)
free(p1); /* If it is a last node,direct to free the memory */
else {
p1->prev->next = p1->next;
p1->next->prev = p1->prev;
free(p1);
}
return TRUE;
}
/* Printf the double chain list*/
void OutputList(DoubleLink *p)
{
DoubleLink *p1;
p1 = p;
while (p1 = p1->next)
printf("%d,", p1->data);
printf("\n");
}
/* free the memory of double chain list If not to use it latter */
void DestoryList(DoubleLink *p)
{
while (p) {
free(p);
p = p->next;
}
}
main()
{
DoubleLink *ptr;
int n, i;
printf("Please input the number of data you want to create:\n");
scanf("%d", &n);
ptr = CreateList(ptr, n);
OutputList(ptr);
printf("Please input the ith where you want to delete:\n");
scanf("%d", &i);
if (DeleteList(ptr, i)) {
printf("Delete success!\n");
OutputList(ptr);
} else
printf("Delete failed!\n");
DestoryList(ptr);
system("PAUSE");
}
---------------------------------
Do You Yahoo!?
嫌邮箱太小?雅虎电邮自助扩容! |