简单的链表相加
一,结构体的构造函数
二,链表相加
1,代码展示,看教程完成的
#include<iostream>using namespace std;struct Node
{int value;Node* next;Node(int x = 0,Node* p = NULL) : value(x) ,next(p) {};
};Node* create_nodelist(int*, int);
Node* add_twolist(Node*, Node*);
void printlist(Node*);int main()
{int arr1[] = { 3,2,6,3,7,9,1 };int arr2[] = { 4,2,5,2,6 };int len1 = sizeof(arr1) / sizeof(int);int len2 = sizeof(arr2) / sizeof(int);Node* head1, * head2,* add_head;head1 = create_nodelist(arr1, len1);printlist(head1);cout << endl;head2 = create_nodelist(arr2, len2);printlist(head2);cout << endl;cout << "the addded_list is below ." << endl;add_head = add_twolist(head1, head2);printlist(add_head);return 0;
}Node* create_nodelist(int* arr, int len)
{Node* head = new Node;Node* current = head;head->value = arr[0];for (int i = 1; i < len; i++){Node* p = new Node;p->value = arr[i];current->next = p;current = p;}current->next = NULL;return head;
}Node* add_twolist(Node* head1, Node* head2)
{Node* ans, * current, * cur1 = head1, * cur2 = head2;ans = current = NULL;int carry = 0;for (int sum, val;cur1 != NULL || cur2 != NULL;cur1 = (cur1 == NULL) ? NULL : cur1->next,cur2 = (cur2 == NULL) ? NULL : cur2->next){sum = (cur1 == NULL ? 0 : cur1->value)+ (cur2 == NULL ? 0 : cur2->value)+ carry;val = sum % 10;carry = sum / 10;if (ans == NULL)//create the new head node {ans = new Node(val);current = ans;}else{current->next = new Node(val);current = current->next;}}if (carry == 1)current->next = new Node(1);return ans;
}void printlist(Node* head)
{Node* current = head;while (current != NULL){cout << current->value << " ";current = current->next;}
}
2,补充
for循环里面条件的宽泛表达,条件更新;充分使用三目运算。