typedef使用
typedef struct node Node;
Node* head;
Node* p;
Node* q;
Node* temp;
malloc和free操作
p=(Node*)malloc(sizeof(Node*));
temp=head;
while(temp != NULL)
{
temp=head->next;
free(head);
head=temp;
}
printf("\n空间已经释放") ;
遍历操作
temp=head;
while(temp != NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
创建一个链表
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
int main()
{
typedef struct node Node;
Node* head;
Node* p;
Node* q;
Node* temp;
int i;
int n;
int a;
head=NULL;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a);
p=(Node*)malloc(sizeof(Node*));
p->data=a;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
temp=head;
while(temp != NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
temp=head;
while(temp != NULL)
{
temp=head->next;
free(head);
head=temp;
}
printf("\n空间已经释放") ;
return 0;
}
在链表中插入数据
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
int main()
{
typedef struct node Node;
Node* head;
Node* p;
Node* q;
Node* temp;
int i;
int n;
int a;
head=NULL;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a);
p=(Node*)malloc(sizeof(Node*));
p->data=a;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
temp=head;
scanf("%d",&a);
while(temp != NULL)
{
if(temp->next==NULL || (temp->next)->data > a)
{
p=(Node*)malloc(sizeof(Node));
p->data=a;
p->next=temp->next;
temp->next=p;
break;
}
temp=temp->next;
}
temp=head;
while(temp != NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
temp=head;
while(temp != NULL)
{
temp=head->next;
free(head);
head=temp;
}
printf("\n空间已经释放") ;
return 0;
}