MP3Three

导航

Leetcode Two Add Two Numbers

前言

题目描述是,给出两个逆序的、用链表表示的数字,将二者相加得到结果,如:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

具体算法

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 
10 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
11     struct ListNode *res = (struct ListNode*)malloc(sizeof(struct ListNode)); // 此指针为头节点,初始化为0,返回res->next
12     res->val = 0;res->next = NULL; // res->next 这个赋值极为重要,如果不赋值为NULL就会出现内存错误
13     struct ListNode *p1 = l1, *p2 = l2, *cur = res; // cur为游标指针,p1、p2用来游标,毕竟不能让l1、l2直接游动,这样会丢失原头指针
14 int carry = 0; 15 while (p1 || p2) { 16 int sum = (p1?p1->val:0) + (p2?p2->val:0) + carry; 17 cur->next = (struct ListNode*)malloc(sizeof(struct ListNode)); 18 cur = cur->next; 19 cur->next = NULL; 20 cur->val = sum % 10; 21 carry = (sum >= 10) ? 1 : 0; // sum/10 also works 22 23 p1 = p1?p1->next:p1; 24 p2 = p2?p2->next:p2; 25 } 26 if (carry > 0) { 27 cur->next = (struct ListNode*)malloc(sizeof(struct ListNode)); 28 cur = cur->next; // cur == rear 29 cur->next = NULL; 30 cur->val = carry; 31 } 32 33 34 return res->next; 35 }

总之,这里的关键有两个:

  • 一是cur->next的地址分配,当cur->next分配空间且cur向后移动后,需要将此时的cur->next设置为NULL,否则会出现内存错误
  • 二是给定两个链表是否遍历完成的判定,这里直接使用 p1?p1->next:p1就是一个很妙的判定

这次的难点主要来源于对链表操作的不熟悉和许多关于结构体的C语言操作不熟悉。

posted on 2020-08-19 22:35  MP3Three  阅读(5)  评论(0)    收藏  举报