单链表问题
这几天准备复试,看到了一个题目
大致意思就是一个单链表,然后将其中的偶数个和奇数个位置的数字分别放在链表head1和head2,看似简单实则试了好长时间,代码在下面。
我用的vs2017,给大家注释好,顺便自己也总结一下。欢迎大佬们提意见
#include<iostream>
#include<stdlib.h>
#include<algorithm>//经典三联头文件
using namespace std;
typedef struct lnode
{
int data;
struct lnode *next;
}lnode,*linklist;
int n=1;
int a[10000] = {};//利用这个数组存放输入的数字
linklist head1, head2;
void tailinsert(linklist &l)//尾插法,将其插入原本的链表l
{
lnode *s,*d;
int i = 1;
int c = 0;
l = (linklist)malloc(sizeof(lnode));
l->next = NULL;
d = l;
cout << "请输入要输入的元素" << endl;
cin >> c;
while (c != 9999)
{
n++;//统计一共输入了多少元素
a[i] = c; i++;
s = (lnode*)malloc(sizeof(lnode));
s->data = c;
d->next = s;
s->next = NULL;
d = s;
cout << "请输入要出入的元素" << endl;
cin >> c;
}
}
void printall(linklist &l)
{
lnode *c;
c = l->next;
while (c != NULL)
{
cout << c->data << endl;
c = c->next;
}
}
int main()
{
linklist l;
tailinsert(l);
printall(l);
head1 = (linklist)malloc(sizeof(lnode));//初始化
head2 = (linklist)malloc(sizeof(lnode));//都初始化一下
head1->next = NULL;
head2->next = NULL;
lnode *s;//用来做中转的节点
lnode *d,*e;
d = head1;
e = head2;//d和e作为可移动的指针
for (int i = 1; i <n; i++)
{
if ((i % 2) == 0)//
{
s = (lnode*)malloc(sizeof(lnode));//尾插法的关键代码
s->data = a[i];
d->next = s;
s->next = NULL;
d = s;
}
else
{
s = (lnode*)malloc(sizeof(lnode));
s->data = a[i];
e->next = s;
s->next = NULL;
e = s;
}
}
cout << "偶数" << endl;
printall(head1);
cout << "奇数" << endl;
printall(head2);
}
如果大家还有什么不明白的可以私聊我,大家一起学习