sigle list:
Add Two Numbers
/*** Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* p1 = l1;
struct ListNode* p2 = l2;
struct ListNode* p = NULL;
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 0;
head->next = NULL;
int x = 0;
int a=0,b=0;
while((p1 != NULL) || (p2 != NULL)||(x != 0))
{
if(p==NULL)
{
p=head;
}
else
{
p->next=(struct ListNode*)malloc(sizeof(struct ListNode));
p = p->next;
}
a = (p1!=0) ? p1->val : 0;
b = (p2!=0) ? p2->val : 0;
p->val = (a + b + x)%10;
x = (a + b + x) / 10;
p1 = (p1!=0)?p1->next:NULL;
p2 = (p2!=0)?p2->next:NULL;
p->next = NULL;
}
return head;
}
注意:单链表尾指针指向空(故应该P->NEXT=NULL),否则会报错
知识点:1.链表中的元素成为节点,节点包含两个域---------指针域和数据域;
2.单向链表通常由一个头指针,用于指向表头;
3.单向链表有一个尾部指针,指向空;