到目前为止,这是我的代码。我在实现主要功能方面遇到了问题,因为链接列表对我来说是一个新主题。有人可以解释一下我应该包含什么来产生这样的输出
在最初的空列表中插入2个,0个,3个,5个和4个后,输出应该如下所示:
2
0 2
0 2 3
0 2 3 5
0 2 3 4 5
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int number;
struct node *next;
} NODE;
NODE* insert(NODE *, int);
NODE* delete(NODE *, int);
void traverse(NODE *);
NODE * search(NODE *head, int data);
main(){
list *newnode, *start = NULL; // this will point to the first node of the list
}
NODE *search(NODE *head, int data){ //search for the right position to add data
NODE *previous=NULL;
NODE *current=head;
while (current !=NULL && data > current->number)
{
previous=current;
current= current->next;
}
return previous;
}
NODE *insert(NODE *head, int data){ //allocates a new node with data value
NODE * temp;
if (temp = (NODE *)malloc(sizeof(NODE)==(NODE*)NULL))
return 1; //malloc have failed
temp->number = data;
NODE *previous;
previous=search(head,data);
//two cases 1) add at front 2)add elsewhere
if (previous==NULL)
{
temp->next=head;
head=temp;
}
else
{
temp->next = previous->next;
previous->next = temp;
}
return head;
}
void traverse (NODE *head){
NODE * current = head;
while (current != NULL)
{
printf(" %d ", current->number);
current = current->next;
}
printf("\n");
}
NODE* delete(NODE *head, int data)
{
NODE *previous, *temp;
previous=search(head,data);
if(previous==NULL && head->number==data)
{
temp=head;
head=head->next;
free(temp);
}
else if (previous->next !=NULL && previous->next->number==data)
{
temp=previous->next;
previous->next = previous->next->next;
free(temp);
}
return head;
}
答案 0 :(得分:0)
void printList (list *currentPtr)
{
if (currentPtr == NULL)
printf("list is empty.\n\n");
else
{
printf("The list is:\n");
while (currentPtr != NULL){
printf("%d --> ", currentPtr->number);
currentPtr = currentPtr ->next;
}
printf("NULL\n\n");
}
}
The list is:
0 -> 2 -> 3 -> 4 -> 5 -> NULL
哟可以带走NULL和 - &gt;如果你愿意的话。