创建链表(加遍历链表):
方法一:头插法
图解如下
代码如下
#include<stdio.h>
#include<stdlib.h> //包含malloc函数
#include<iostream>
using namespace std;
struct Linklist
{
int data;
struct Linklist* next;
};
//遍历链表
void travelLinklist(struct Linklist *head)
{
struct Linklist *p;
p = head;
while (p->next != NULL)
{
cout << p->next->data << " ";
p = p->next;
}
}
int main()
{
struct Linklist* head = (struct Linklist*)malloc(sizeof(struct Linklist));
//cout << sizeof(struct Linklist);
head->next = NULL;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
struct Linklist* s = (struct Linklist*)malloc(sizeof(struct Linklist));
cin >> s->data;
//头插法创建链表关键语句
s->next = head->next;
head->next = s;
}
travelLinklist(head);
return 0;
}
方法二:尾插法
图解如下
代码如下
#include<stdio.h>
#include<stdlib.h> //包含malloc函数
#include<iostream>
using namespace std;
struct Linklist
{
int data;
struct Linklist* next;
};
//遍历链表
void travelLinklist(struct Linklist *head)
{
struct Linklist *p;
p = head;
while (p->next != NULL)
{
cout << p->next->data << " ";
p = p->next;
}
}
int main()
{
struct Linklist* head = (struct Linklist*)malloc(sizeof(struct Linklist));
head->next = NULL;
struct Linklist* p;
p = head;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
struct Linklist* s = (struct Linklist*)malloc(sizeof(struct Linklist));
cin >> s->data;
p->next=s;
s->next = NULL;
p = s;
}
travelLinklist(head);
return 0;
}
请注意头插法与尾插法遍历数据的区别