带头结点的单链表创建常用2种方法
带头结点的单链表创建有两种,尾部插法和头部插法。
尾部插法:
每次都在链表的最后插入,最先输入的结点最先输出,最后输入的结点最后输出。例如,输入是:1,2,3,4,5。输出为:1,2,3,4,5。
#include <stdio.h>
#include "malloc.h"
struct node
{
int data;
struct node *next;
};
struct node *CreatListTail(int n) /*表尾插入法创建*/
{
struct node *head,*pf,*pb;
int i;
printf("Please input %d nodes (int) : ",n);
pb=(struct node *)malloc(sizeof(struct node));
pf=head=pb; head->next=NULL;
for(i=0;i<n;i++)
{
pb=(struct node *)malloc(sizeof(struct node));
scanf("%d",&pb->data);
pb->next=pf->next;
pf->next=pb;
pf=pb; //标记表尾节点的位置
}
return head;
}
void printList(struct node *p)
{
p = p->next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
}
int main()
{
int n;
struct node *list;
printf("Input the number of nodes in the list:");scanf("%d",&n);
list = CreatListTail(n);
printf("Print the new list: ");
printList(list);
}
头部插法:
每次都在链表的前面插入(头结点的后面),最先输入的结点最后输出,最后输入的结点最先输出。例如,输入是:1,2,3,4,5。输出为:5,4,3,2,1。
#include <stdio.h>
#include "malloc.h"
struct node
{
int data;
struct node *next;
};
struct node *CreatListHead(int n) /*表头插入法创建*/
{
struct node *head,*pf,*pb;
int i;
printf("Please input %d nodes (int) : ",n);
pb=(struct node *)malloc(sizeof(struct node));
pf=head=pb; head->next=NULL;
for(i=0;i<n;i++)
{
pb=(struct node *)malloc(sizeof(struct node));
scanf("%d",&pb->data);
pb->next=pf->next;
pf->next=pb;
}
return head;
}
void printList(struct node *p)
{
p = p->next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
}
int main()
{
int n;
struct node *list;
printf("Input the number of nodes in the list:");scanf("%d",&n);
list = CreatListHead(n);
printf("Print the new list: ");
printList(list);
}