两数相加官方答案:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *head = NULL, *tail = NULL;
int carry = 0; //换位
while (l1 || l2) { //l1或l2不为空
int n1 = l1!=NULL ? l1->val : 0; //l1不为空n1=l1的值
int n2 = l2!=NULL ? l2->val : 0;
int sum = n1 + n2 + carry;
if (!head) { //如果head为空
head = tail = malloc(sizeof(struct ListNode)); //申请一个列表
tail->val = sum % 10;
tail->next = NULL;
}
else {
tail->next = malloc(sizeof(struct ListNode));
tail->next->val = sum % 10;
tail = tail->next;
tail->next = NULL;
}
carry = sum / 10;
if (l1) { //将l1后移一位
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
if (carry > 0) { //如果最后carry>0申请一个新的尾节点
tail->next = malloc(sizeof(struct ListNode));
tail->next->val = carry;
tail->next->next = NULL;
}
return head;
}
删除链表中的节点:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
node->val=node->next->val;
node->next=node->next->next;
}