链表相加详解程序员
2023-06-13 09:20:21 时间
给定两个链表,分别表示两个非负整数,他们的数字逆序存储在链表中,且每个节点只存储一个数字,计算两个数的和,并且返回和的链表头指针
如:输入:2-4-3,5-6-4 输出:7-0-8
因为两个数都是逆序存储,正好可以从头向后依次相加,完成“两个数的竖式计算”
pHead1:4-9-0-4-7-1
pHead2:1-7-1-5-5-4-2-8
pHead3:5-6-2-9-2-6-2-8
以下为实现代码:
#include stdio.h #include stdlib.h typedef struct Node{ int data; struct Node *next; }Node,*pNode; void print(pNode p){ //打印链表 while(p){ printf("%d ",p- data); p=p- next; printf("/n"); pNode Add(pNode pHead1,pNode pHead2){ //计算链表相加的值 pNode p1=pHead1- next; pNode p2=pHead2- next; pNode pCur; pNode p3 = (pNode)malloc(sizeof(Node)); p3- data=0; p3- next =NULL; int carry = 0; //进位 int value = 0; while(p1 p2){ value = p1- data + p2- data + carry; carry = value/10; value %= 10; pCur=(pNode)malloc(sizeof(Node)); pCur- data=value; pCur- next=p3- next; p3- next=pCur; p1=p1- next; p2=p2- next; pNode p=p1 ? p1:p2; while(p){ //计算较长的链表 value = p- data+carry; carry /= 10; value %= 10; pCur=(pNode)malloc(sizeof(Node)); pCur- data=p- data+carry; pCur- next=p3- next; p3- next=pCur; p = p- next; if(carry!=0){ pCur=(pNode)malloc(sizeof(Node)); pCur- data=carry; pCur- next=p3- next; p3- next=pCur; return p3; void destroy(pNode p){ //销毁链表 pNode temp=p; while(p- next != NULL){ temp=p- next; p=temp- next; free(temp); int main(){ int a[6]={1,7,4,0,9,4}; int b[8]={8,2,4,5,5,1,7,1}; pNode pHead1 = (pNode)malloc(sizeof(Node)); pHead1- data = 0; pHead1- next =NULL; for(int i=0;i i++){ pNode p=(pNode)malloc(sizeof(Node)); p- data=a[i]; p- next=pHead1- next; pHead1- next=p; pNode pHead2 = (pNode)malloc(sizeof(Node)); pHead2- data = 0; pHead2- next =NULL; for(int j=0;j j++){ pNode p=(pNode)malloc(sizeof(Node)); p- data=b[j]; p- next=pHead2- next; pHead2- next=p; print(pHead1- next); print(pHead2- next); pNode pHead3 = Add(pHead1,pHead2); print(pHead3- next); destroy(pHead1); destroy(pHead2); destroy(pHead3); system("pause"); }
结果为:
4 9 0 4 7 1
1 7 1 5 5 4 2 8
8 2 6 2 9 2 6 5
请按任意键继续. . .
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/7222.html
服务器部署程序员系统优化网站设置运维相关文章
- 【大厂高频算法题】反转链表
- 彻底搞懂React-hook链表构建原理
- 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
- C语言链表和关键字typedef
- C 单向链表排序_单向链表排序java
- 单向链表实现约瑟夫环
- 数据结构实验之链表七:单链表中重复元素的删除(SDUT 2122)
- 链表相关知识
- 算法-从尾到头打印链表详解编程语言
- Linux内核之美:链表表现力(linux内核链表)
- Oracle数据库中使用的链表结构技术分析(oracle中链表结构图)
- 利用Redis实现高效的链表结构(redis 链表结构体)
- 红色的解决之路使用Redis链表(redis链表怎么用)