單鏈表頭插法與尾插法的c語言實現(回顧)
阿新 • • 發佈:2019-01-02
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
typedef struct node{
int data;
node *next;
};
int main()
{
node *head = NULL;
node *tail = NULL;
node *p = NULL;
p = (node *)malloc(sizeof(node));
if(p==NULL){
printf("%s","沒有足夠的空間");
}
head = p;
tail = p;
for (int i=0;i<10;i++){
node *pnew = (node*)malloc(sizeof(node));
pnew ->data = i;
//頭插法:逆序
if(i==0){
pnew ->next = NULL;
head ->next = pnew;
}else{
pnew ->next = head->next;
head ->next = pnew;
}
//尾插法
//pnew ->next = NULL;
//p -> next = pnew;
//p = p->next;
}
head = head->next;
while(head!=NULL){
printf("%d ",head->data);
head = head->next;
}
return 0;
}