题目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
实现:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
void traverseList(struct ListNode *headNode);
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2);
int main(int argc, const char * argv[]) {
struct ListNode *node_1 = malloc(sizeof(struct ListNode));
node_1->val = 5;
node_1->next = NULL;
struct ListNode *node_4 = malloc(sizeof(struct ListNode));
node_4->val = 5;
node_4->next = NULL;
traverseList(node_1);
traverseList(node_4);
struct ListNode *resultNode = addTwoNumbers(node_1, node_4);
traverseList(resultNode);
return 0;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
//结构指针,首地址指针
struct ListNode *resultNode = malloc(sizeof(struct ListNode));
resultNode->val = 0;
resultNode->next = NULL;
//用来存放进位值
int carryNum = 0;
//遍历指针
struct ListNode *p1 = l1, *p2 = l2, *p3 = resultNode;
//循环处理O(n)
while (p1 != NULL || p2 != NULL) {
if (NULL != p1) {
carryNum += p1->val;
p1 = p1->next;
}
if (NULL != p2) {
carryNum += p2->val;
p2 = p2->next;
}
p3->next = malloc(sizeof(struct ListNode));
p3 = p3->next;
p3->val = carryNum % 10;
p3->next = NULL;
carryNum /= 10;
}
if (0 != carryNum) {
p3->next = malloc(sizeof(struct ListNode));
p3 = p3->next;
p3->val = carryNum % 10;
p3->next = NULL;
}
return resultNode->next;
}
/**
遍历单链表
@param headNode 单链表头结点指针
*/
void traverseList(struct ListNode *headNode) {
//游标指针
struct ListNode *p = headNode;
while (NULL != p) {
if (NULL != p->next) {
printf("%d->",p->val);
}else {
printf("%d",p->val);
}
p = p->next;
}
printf("\n");
}
网友评论