您的位置:首页 > 其它

单向链表创建

2016-03-11 14:31 267 查看
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

struct link
{
int data;
struct link *next;
};

typedef struct link lb;

lb *creatlink(int n)
{
lb *head,*p,*q;
int x;
head=q=(lb*)malloc(sizeof(lb));
if(head!=NULL)
{
head->next=NULL;
for(int i=0;i<n;i++)
{
p=(lb*)malloc(sizeof(lb));
cin>>p->data;
q->next=p;
q=q->next;
}
}
q->next=NULL;
return head;
}

void out(lb *head)
{
struct link *p=head;
while(p!=NULL&&p->next!=NULL)
{
p=p->next;
cout<<p->data<<" "<<endl;
}
}

void freelink(lb *head)
{
lb *p=head;
lb *q=NULL;
while(p!=NULL)
{
q=p;
p=p->next;
free(q);

}
}
int main()
{int n;
struct link *head;
while(cin>>n)
{
head=creatlink(n);
out(head);
free(head);
}

return 0;
}


in:5

1 5 7 9 4

out:1

5

7

9

4

逆向创建

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

struct antilink
{
int data;
struct antilink *next;
};

typedef struct antilink al;

al *creatlink()
{
al *p,*q;
int x;
cin>>x;
while(x!=0)
{
p=(al*)malloc(sizeof(al));
p->data=x;
p->next=q;
q=p;
cin>>x;
}
return q;
}

void out(al*head)
{
al *p=head;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}

void freelist(al*head)
{
al *p=head;
al *q=NULL;
while(p!=NULL)
{
q=p;
p=p->next;
free(q);
}
}
int main()
{al *head;
head=creatlink();
out(head);
freelist(head);

return 0;
}


in:1 2 3 4 5

out:5 4 3 2 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: