版权声明:转载请注明出处 https://blog.csdn.net/nanhuaibeian/article/details/88376378
题目
建立一个带头结点的线性链表,用以存放输入的二进制数,链表中每个结点的data域存放一个二进制位。
在此链表上实现对二进制数加1的运算,并输出运算结果
测试数据1: 1010011
测试数据2 1111
代码
#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(node)
#define max 100
typedef struct node {
int data;
struct node *next;
}*linklist,node;
//创建二叉链表,采用二叉链表
void creat(linklist *head) {
linklist s,r;
int data;
*head = (linklist)malloc(LEN);
(*head)->next = NULL;
r = *head;
printf("请输入二进制数:\n");
scanf("%d",&data);
// 以100作为输入结束
while(data!=100) {
s = (linklist)malloc(LEN);
s->data = data;;
r->next = s;
r = s;
scanf("%d",&data);
}
r->next = NULL;
}
void main() {
linklist head,r,p,s;
creat(&head);
r = p = head->next;
// 寻找最后数中的最后一个值为0的节点,将其赋值给r
while(p!=NULL) {
if(p->data==0) r=p;
p=p->next;
}
//如果数中不存在0,即全为1,则新建一个结点,头插法插入链表首
if(r==head->next){
s = (linklist)malloc(LEN);
s->data = 1;
s->next = head->next;
head->next = s;
r = s;
}
else r->data =1;
// 将r结点之后的结点值置为0
r = r->next;
while(r!=NULL){
r->data = 0;
r = r->next;
}
// 输出节点
p = head->next;
while(p!=NULL){
printf("%d ",p->data);
p = p->next;
}
}