#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}*PNode,Node;
void init(PNode *p);
void Create(PNode Head);
void printfValue(PNode Head);
void BinAdd(PNode Head);
int main()
{
PNode Head;
init(&Head);
Create(Head);
printfValue(Head);
printf("输出二进制相加以后的值:\n");
BinAdd(Head);
printfValue(Head);
return 0;
}
void init(PNode *p)
{
(*p) = (PNode)malloc(sizeof(Node));
(*p)->next = NULL;
}
void Create(PNode Head)
{
PNode r,s;
int n = 0,m;
r = Head;
printf("请输入m个结点:\n");
scanf("%d",&m);
printf("请输入每个结点的值:\n");
while(n < m)//尾插法
{
s = (PNode)malloc(sizeof(Node));
scanf("%d",&s->data);
r->next = s;
r = s;
n++;
}
r->next = NULL;
//
}
void printfValue(PNode Head)
{
printf("输出各个结点的值:\n");
PNode p;
p = Head->next;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
void BinAdd(PNode Head)
{
PNode q,r,s;
q = Head->next;
r = Head;
while(q != NULL)//查找最后一个元素为0的结点
{
if(q->data == 0)
{
r = q;
}
q = q->next;
}
if(r != Head)//在单链表中找到最后一个data域为0的结点
{
r->data = 1;//找到最后一个值为0 的结点值域为1
}
else
{
//temp = r->next;
s = (PNode)malloc(sizeof(Node));
s->data = 1;
s->next = r->next;
s->next = s;
r = s;
}
r = r->next;
while(r != NULL)
{
r->data = 0;
r = r->next ;
}
}