~~~How can the writing style end in a dull way, and the story does not recognize ordinary at the beginning ✌✌✌
If you need the complete code, you can follow the public account below, and reply "code" in the background to get it. Aguang is looking forward to your visit~
Title:
Decompose a singly linked list A with a head node into two singly linked lists A and B with head nodes, so that the A table contains the odd-numbered elements in the original table, and the B table contains the even-numbered elements in the original table , and keep their relative order unchanged.
Problem solving ideas:
>定义位置变量,用于指示节点序号
>然后定义两个尾指针,分别判断节点序号奇偶
>使用尾插法进行插入
Code:
#include <iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LinkList;
// 头插法
void HeadInsert(LinkList &L)
{
int val = 0;
while (cin >> val)
{
LNode *s = new LNode;
s->data = val;
s->next = L->next;
L->next = s;
if (cin.get() == '\n')
{
break;
}
}
}
// 尾插法
void TailInsert(LinkList &L)
{
int val = 0;
LNode *r = L;
while (cin >> val)
{
LNode *s = new LNode;
s->data = val;
r->next = s;
r = s;
r->next = NULL;
if (cin.get() == '\n')
{
break;
}
}
}
// 遍历输出链表元素
void Print(LinkList L)
{
LNode *p = L->next;
while (p)
{
cout << p->data << '\t';
p = p->next;
}
cout << endl;
}
void BreakList(LinkList &LA, LinkList &LB)
{
int i = 1;
LNode *p, *ra, *rb;
p = LA->next;
ra = LA, rb = LB;
ra->next = NULL, rb->next = NULL;
while (p)
{
if (i % 2 == 1)
{
ra->next = p;
ra = p;
}
else
{
rb->next = p;
rb = p;
}
p = p->next;
i++;
}
ra->next = NULL;
rb->next = NULL;
}
int main()
{
LinkList LA = new LNode;
LinkList LB = new LNode;
TailInsert(LA);
BreakList(LA, LB);
Print(LA);
Print(LB);
}