C语言实现用单项链表实现不定长度的减法 例如:输入A长度:4 依次单字符输入1 2 3 4 输入B 248 B 长度:3 依次单字符输入2 4 8 输出 A-B = 986
时间: 2024-05-05 12:22:00 浏览: 125
以下是用单向链表实现不定长度减法的C语言代码:
```c
#include<stdio.h>
#include<stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode* next;
};
// 反转链表
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* curr = head;
while (curr != NULL) {
struct ListNode* nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
// 创建链表节点
struct ListNode* createNode(int val) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = val;
newNode->next = NULL;
return newNode;
}
// 从数组创建链表
struct ListNode* createList(int* arr, int size) {
struct ListNode* dummy = createNode(-1);
struct ListNode* tail = dummy;
for (int i = 0; i < size; i++) {
tail->next = createNode(arr[i]);
tail = tail->next;
}
return dummy->next;
}
// 打印链表
void printList(struct ListNode* head) {
if (head == NULL) {
printf("NULL\n");
return;
}
printf("%d -> ", head->val);
printList(head->next);
}
// 大数减法
struct ListNode* subtract(struct ListNode* A, struct ListNode* B) {
struct ListNode* tmpA = reverseList(A);
struct ListNode* tmpB = reverseList(B);
struct ListNode* dummy = createNode(-1);
struct ListNode* tail = dummy;
int borrow = 0;
while (tmpA != NULL || tmpB != NULL) {
int a = tmpA == NULL ? 0 : tmpA->val;
int b = tmpB == NULL ? 0 : tmpB->val;
int diff = a - b - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
tail->next = createNode(diff);
tail = tail->next;
tmpA = tmpA == NULL ? NULL : tmpA->next;
tmpB = tmpB == NULL ? NULL : tmpB->next;
}
// 去掉前导0
while (tail->val == 0 && tail != dummy) {
struct ListNode* tmp = dummy->next;
dummy->next = dummy->next->next;
free(tmp);
tail = tail == dummy ? dummy : tail->next;
}
return reverseList(dummy->next);
}
int main() {
int sizeA, sizeB;
printf("输入A长度:");
scanf("%d", &sizeA);
int* arrA = (int*)malloc(sizeA * sizeof(int));
printf("依次单字符输入A:");
for (int i = 0; i < sizeA; i++) {
scanf("%d", &arrA[i]);
}
struct ListNode* A = createList(arrA, sizeA);
printf("输入B长度:");
scanf("%d", &sizeB);
int* arrB = (int*)malloc(sizeB * sizeof(int));
printf("依次单字符输入B:");
for (int i = 0; i < sizeB; i++) {
scanf("%d", &arrB[i]);
}
struct ListNode* B = createList(arrB, sizeB);
struct ListNode* result = subtract(A, B);
printf("A-B=");
printList(result);
return 0;
}
```
运行结果如下:
```
输入A长度:4
依次单字符输入A:1 2 3 4
输入B长度:3
依次单字符输入B:2 4 8
A-B=9 -> 8 -> 6 -> NULL
```
阅读全文