尾插法建立建表
typedef struct node {
int value;
struct node* next;
}node, * Linklist;
void creatlist(Linklist &l)
{
Linklist tp;
Linklist lst;
l = NULL;
l = (Linklist)malloc(sizeof(node));
lst = l;
int a;
while (cin >> a && a > 0)
{
tp = (Linklist)malloc(sizeof(node));
tp->value = a;
lst->next = tp;
lst = tp;
}
lst->next = NULL;
}
头插法建立链表
typedef struct node {
int value;
struct node* next;
}node, * List;
void creatlist(List& L)
{
List p;
int tp;
L = (List)malloc(sizeof(node));
L->next = NULL;
while (cin >> tp && tp >= 0)
{
p = (node *)malloc(sizeof(node));
p->value = tp;
p->next = L->next;
L->next = p;
len++;
}
}
相关题目
头插法
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct node {
int value;
struct node* next;
}*Linklist, node;
void creatlist(Linklist &l)
{
Linklist tp;
Linklist lst;
l = NULL;
l = (Linklist)malloc(sizeof(node));
lst = l;
int a;
while (cin >> a && a > 0)
{
tp = (Linklist)malloc(sizeof(node));
tp->value = a;
lst->next = tp;
lst = tp;
}
lst->next = NULL;
}
int main()
{
Linklist L1, L2;
creatlist(L1);
creatlist(L2);
node* a, * b;
a = L1->next;
b = L2->next;
int cnt = 0;
while (a != NULL && b != NULL)
{
if (a->value == b->value)
{
if(!cnt)
cout << a->value;
else
{
cout << " " << a->value;
}
a = a->next;
b = b->next;
}
else
{
if (a->value < b->value)
{
if (!cnt)
cout << a->value;
else
{
cout << " " << a->value;
}
a = a->next;
}
else
{
if (!cnt)
cout << b->value;
else
{
cout << " " << b->value;
}
b = b->next;
}
}
cnt++;
}
while (a != NULL)
{
if (!cnt)
cout << a->value;
else
{
cout << " " << a->value;
}
a = a->next;
}
while (b != NULL)
{
if (!cnt)
cout << b->value;
else
{
cout << " " << b->value;
}
b = b->next;
}
return 0;
}
尾插法
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef struct node {
int value;
struct node* next;
}node, * List;
int len;
void creatlist(List& L)
{
List p;
int tp;
L = (List)malloc(sizeof(node));
L->next = NULL;
while (cin >> tp && tp >= 0)
{
p = (node *)malloc(sizeof(node));
p->value = tp;
p->next = L->next;
L->next = p;
len++;
}
}
int main()
{
//换成scanf或者用那个语句加速输入输出,否则这个代码会TLE
int cnt = 0;
int bk = 0;
int k;
cin >> k;
List La;
int flag = 0;
creatlist(La);
node* p;
p = La;
while (p)
{
if (flag == k)
{
bk = 1;
break;
}
flag++;
p = p->next;
}
if (!bk)
{
cout << "NULL";
}
else
cout << p->value;
return 0;
}