构建,打印,释放,添加元素
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node{
int data;
struct node*next;
}Node;
void add(int a,Node*head);
void print(Node*head);
void freelist(Node*head);
int main()
{
Node*head=(Node*)malloc(sizeof(Node*));
head->next=NULL;
int a;
cin>>a;
head->data=a;
while(cin>>a)
{
add(a,head);
}
print(head);
freelist(head);
return 0;
}
void add(int a,Node*head)
{
Node*current=head;
Node*add=(Node*)malloc(sizeof(Node*));
add->data=a;
add->next=NULL;
while(current->next!=NULL) current=current->next;
current->next=add;
}
void print(Node*head)
{
Node*current=head;
cout<<current->data<<" ";
while(current->next!=NULL)
{
current=current->next;
cout<<current->data<<" ";
}
cout<<endl;
}
void freelist(Node*head)
{
Node*last=NULL;
while(head->next!=NULL)
{
last=head;
head=head->next;
free(last);
}
free(head);
}