简而言之,我应该有"1234568910".
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next;
} SLNode;
void ListInitiate(SLNode **head) /* Initialization */
{
/* If there is memory space, apply the head node space and make the head pointer point to the head node */
if((*head = (SLNode *)malloc(sizeof(SLNode))) == NULL) exit(1);
(*head)->next = NULL; /* set the last of the list as Null */
}
int ListLength(SLNode *head) /* Get the size of the linked list */
{
SLNode *p = head;
int size = 1;
while(p->next != NULL) /*count with loop*/
{
p = p->next;
size ++;
}
return size;
}
int ListInsert(SLNode *head, int i, DataType x)
/* Insert a node that contains the data element x before the node ai (0 ≤ i ≤ size) of the linked list with header */
{
SLNode *p, *q;
int j;
p = head; /* p points to the head*/
j = -1; /* the initial value of j is -1*/
while(p->next != NULL && j < i - 1)
/* Finally let pointer p point to data element ai-1 node */
{
p = p->next;
j++;
}
if(j != i - 1)
{
printf("Insert position parameter wrong!");
return 0;
}
/* q points to the new node*/
if((q = (SLNode *)malloc(sizeof(SLNode))) == NULL) exit(1);
q->data = x;
/* There is an error blow*/
q->next = p->next;
p->next = q;
return 1;
}
int ListDelete(SLNode *head, int i, DataType *x)
/* delete the node ai of the list with a header*/
/* put the data element of the node in x. If success, return 1; if fail, return 0*/
{
SLNode *p, *s;
int j;
p = head;
j = -1;
while(p->next != NULL && p->next->next!= NULL && j < i - 1)
/*Finally let pointer p point to data element ai-1 node */
{
p = p->next;
j++;
}
if(j!= i - 1)
{
printf("Insert position parameter wrong!");
return 0;
}
s = p->next; /*s points to ai*/
*x = s->data; /*Assign the data field value of the node pointed by pointer s to x */
p->next = s->next; /* delete ai*/
free(s); /* free the memory space of s */
return 1;
}
int ListGet(SLNode *head, int i, DataType *x)
/*The function of taking the data element ai is similar to deleting ai function, but do not delete the data element ai node*/
{
SLNode *p;
int j;
p = head;
j = 0;
while(p->next != NULL && j < i)
{
p = p->next;
j++;
}
if(j != i)
{
printf("The position of the parameter is wrong!");
return 0;
}
*x = p->data;
return 1;
}
void Destroy(SLNode **head)
{
SLNode *p, *p1;
p = *head;
while(p != NULL)
{
p1 = p;
p = p->next;
free(p1);
}
*head = NULL;
}
void main(void)
{
SLNode *head;
int i , x;
ListInitiate(&head);
for(i = 0; i < 10; i++)
{
if(ListInsert(head, i, i+1) == 0) /*insert ten data elements*/
{
printf("Error!! \n");
return;
}
}
if(ListDelete(head, 4, &x) == 0) /* delete data element 5*/
{
printf("error! \n");
return;
}
for(i = 0; i < ListLength(head); i++)
{
if(ListGet(head, i, &x) == 0) /* take out the element*/
{
printf("Error! \n");
return;
}
else printf("%d ", x); /* show data elements*/
}
Destroy(&head);
}