将已有带头结点链表L1中的数据均为四位整数,将符合条件a+b>c+d(设四位数为abcd,并且千位+百位>十位+个位)的元素从L1中删除,并将这些删除的结点使用头插方法建立到带头结点链表L2中。创建链表为头插法,0表示创建链表结束。
-
s在前,p在后,s位置不满足条件,p再跳过来,s再前移
#define _CRT_SECURE_NO_WARNINGS
//带头结点链表,多项式求积
#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
int data;
struct _node* next;
} Node, * pNode, * Link;
int create(Link head);
void output(Link head);
void destroy(Link head);
void function(Link h1, Link h2);
int main(void)
{
int flag = 0;
Link L1 = NULL, L2 = NULL;
L1 = (pNode)malloc(sizeof(Node)); //头结点
if (L1 == NULL)
{
return 0;
}
L1->next = NULL;
L2 = (pNode)malloc(sizeof(Node)); //头结点
if (L2 == NULL)
{
free(L1);
return 0;
}
L2->next = NULL;
printf("Input L1's data:\n");
flag = create(L1);
if (flag <= 0)
{
return 0;
}
printf("L1: ");
output(L1);
function(L1, L2);
printf("Output:\n");
printf("L1: ");
output(L1);
printf("L2: ");
output(L2);
destroy(L1);
return 0;
}
int create(Link head)
{
pNode p;
int temp;
if (head == NULL)
{
return -1;
}
scanf("%d", &temp);
while (temp != 0)
{
p = (pNode)malloc(sizeof(Node));
if (p == NULL)
{
destroy(head);
return -1;
}
p->data = temp;
p->next = head->next;
head->next = p;
scanf("%d", &temp);
}
return 1;
}
void output(Link head)
{
if (head != NULL)
{
head = head->next;
}
while (head != NULL)
{
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
void destroy(Link head)
{
pNode p;
if (head == NULL)
{
return;
}
while (head != NULL)
{
p = head->next;
free(head);
head = p;
}
}
/******start******/
void function(Link h1, Link h2) {
int i, t5, t[4];
Link p, q, s, m;
p = h1; q = h2, s = h1->next;
while (s != NULL) {
t5 = s->data;
for (i = 0; i < 4; i++) {
t[i] = t5 % 10;
t5 /= 10;
}
if ((t[0] + t[1]) < (t[2] + t[3])) {
m = s->next;//临时存
s->next = h2->next;//头插
h2->next = s;
p->next = m;
s = m;
}
else {
p = s;//s位置不满足条件,p再跳过来
s = s->next;
}
}
}
/******start******/