对链表的操作今天上课听的有点懵,没反应过来,主要还是当时没学太好,所以忘得更彻底,刚刚重新学了一波,赶紧总结一下:
题目:
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
Input

第一行输入整数的个数N;

第二行依次输入每个整数。

输出这组整数。
Sample Input

8
12 56 4 6 55 15 33 62

Sample Output

12 56 4 6 55 15 33 62

Hint
不得使用数组!
这是顺序建立链表,先附上代码,下面是介绍

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn=1e5+7;
const int INF=1e5+7;
struct node{
    ll date;
    struct node *next;
}*head,*t,*p;
int main()
{
    ll n;
    scanf("%lld",&n);
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    t=head;
    for(int i=1;i<=n;i++)
    {
        p=(struct node *)malloc(sizeof(struct node));
        scanf("%lld",&p->date);
        p->next=NULL;
        t->next=p;
        t=p;
    }
    p=head->next;					//建立完链表后,将p指向头节点的nest,然后可以往后遍历。
    while(p!=NULL)
    {
       // printf("%lld",p->date);
        if(p->next!=NULL)
            printf("%lld ",p->date);
        else
            printf("%lld\n",p->next);
        p=p->next;
    }
    return 0;
}

对于顺序建立链表,首先都要建立头节点,然后我们要借助另外一个node类型的指针变量 t,先将head 赋给t,然后对要接在后面的每个节点p先令p->next 指向NULL,然后将能代表头节点的t,t->next=p,这样就把p接到head的后面,然后让t=p,继续输入,继续往后接。
如果觉得表述不清,用图表示(晚上画的,不太清楚也不太好看):
顺序建立链表
顺序建立链表
本来还想再写个逆序和插入节点,但明天还要早起去练方队,明天再补上把。

相关文章: