链表

来源:互联网 发布:java选择题及答案解析 编辑:程序博客网 时间:2024/06/14 03:29

链表的创建

用head,p1,p2三个指针,分别指向头结点,新创建的结点,最后的结点。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<algorithm>
using namespace std;
struct node
{
    int a;
    struct node *next;
};
int main()
{
    int n;
    cin>>n;
    n--;
    node *head,*p1=NULL,*p2=NULL;
    p1=(struct node *)malloc(sizeof(struct node));
    head=p1;
    cin>>p1->a;
    p2=p1;
    while(n--)
    {
        p1=(struct node *)malloc(sizeof(struct node));
        cin>>p1->a;
        p2->next=p1;
        p2=p1;
    }
    p2->next=NULL;
    p1=head;
    while(p1->next!=NULL)
    {
        cout<<p1->a<<endl;
        p1=p1->next;
    }
    cout<<p1->a;
    free(p1);
    p1=NULL;
    return 0;
}

链表的比较好的博客文章http://blog.csdn.net/hackbuteer1/article/details/6591486/:

0 0
原创粉丝点击