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

xiaoxiao2021-02-28  47

#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; }
转载请注明原文地址: https://www.6miu.com/read-2300216.html

最新回复(0)