单链表头插法与尾插法的c语言实现(回顾)

#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;
}

猜你喜欢

转载自blog.csdn.net/dreamzuora/article/details/80896552