The head and tail insertion method of the establishment of singly linked list

#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}lnode;
void createtail(lnode *l)//尾插法 
{
  lnode *r,*s;
     int x;
cin>>x;
r=l;
while(x!=0)
{ s=(lnode *)malloc(sizeof(lnode)); s->data=x; r->next=s; r=s; cin>>x; } r->next=NULL; } void createhead(lnode *l) //头插法  {    lnode *s;    int x;    cin>>x;    while(x!=0)    {

















       s=(lnode *)malloc(sizeof(lnode));
   s->data=x;
   s->next=l->next;
   l->next=s;
   cin>>x;    }  void print(lnode *l) { lnode *p; p=l->next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } } int main() { lnode *p,*q; p=(lnode *)malloc(sizeof(lnode)); p->next=NULL; createtail(p); print(p); cout<<endl;     q=(lnode *)malloc(sizeof(lnode)); q->next=NULL; createhead(q); print(q); return 0; }

























Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325608651&siteId=291194637