单链表的摧毁。 运行结果在后文。
SLNode* destroy(SLNode *head)
{
SLNode *p,*q;
p=head->next;
head->next=NULL;
q=NULL;
while(q!=NULL)
{
q=p;
p=p->next;
free(q);
q=NULL;
}
printf("sucess!");
}
完整代码:
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct Node{
int data;
struct Node* next;
}SLNode;
SLNode* head_create(){//创建头结点
SLNode* head = (SLNode*)malloc(sizeof(SLNode));
if(head==NULL) exit(1);
head->next=NULL;
return head;
}
SLNode* Node_insert(SLNode *head,int i,int x)//把x插入i位置 ,从头结点开始遍历
{
SLNode *p;p=head;//p指向头结点
int m=0;
while(m<i-1)//遍历到i-1位
{
p=p->next;
m++;
}
SLNode *q = (SLNode*)malloc(sizeof(SLNode));
q->next=p->next;
p->next=q;
q->data=x;
}
SLNode* Node_delete(SLNode *head,int i)//删除i位置的结点
{
SLNode *p,*s;
p=head;
int m=0;
while(m<i-1){//遍历到i-1位
p=p->next;
m++;
}
s=p->next;
p->next=s->next;
free(s);
}
int SL_length(SLNode *head)//链表长度
{
SLNode *p;p=head;
int n=0;
while(p->next!=NULL)
{
n++;
p=p->next;
}
return n;
}
int get_num(SLNode *head,int i)//取链表i位置的数据
{
SLNode *p;p=head;
for(int k=0;k<i;k++)
{
p=p->next;
}
return p->data;
}
void print_SL(SLNode *head)//打印链表
{
SLNode *p;p=head;
if(p==NULL) printf("单链表空!\n");
else{
printf("head");
p=p->next;
}
while(p!=NULL)
{
printf("->%d",p->data);
p=p->next;
}
printf("\n");
}
SLNode* destroy(SLNode *head)
{
SLNode *p,*q;
p=head->next;
head->next=NULL;
q=NULL;
while(q!=NULL)
{
q=p;
p=p->next;
free(q);
q=NULL;
}
printf("sucess!");
}
main()
{
int x,y;
SLNode *SL1=head_create();
for(int i=1;i<10;i++)
{
Node_insert(SL1,i,i*i);//把i^2插入i的位置
}
printf("单链表1为:\n");
print_SL(SL1);
printf("单链表长度为%d\n",SL_length(SL1));
x=3;
Node_delete(SL1,x);//删去第3个位置的结点
printf("删去第%d个结点后单链表为:\n",x);
print_SL(SL1);
printf("单链表长度为%d\n",SL_length(SL1));
y=6;
int num1=get_num(SL1,y);
printf("取第%d个元素为%d\n\n",y,num1);
destroy(SL1);
return 0;
}
运行结果: