自学内容网 自学内容网

两个链表相加【c语言】

比如输入1->2->3, 1->2->4,输出:2->4->7

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;

// 创建一个新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Error! Unable to create a new node.\n");
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
if (*head == NULL) {
*head = createNode(data);
}
else {
Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = createNode(data);
}
}

// 打印链表
void printList(LinkedList head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

int getListLength(Node* node)
{
int length = 0;
Node *tail = node;
while (node != NULL)
{
node = node->next;
length++;
}
return length;
}

LinkedList reverseList(Node* head)
{
Node* pre = NULL;
Node* cur = head;
while (cur != NULL)
{
Node* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}

LinkedList addNodeList(Node* head1, Node* head2)
{
Node* list1 = reverseList(head1);
Node* list2 = reverseList(head2);

Node* newHead = (Node*)malloc(sizeof(Node));
newHead->data = 0;
newHead->next = NULL;

Node* cur = newHead;
int carry = 0;  //进位
while (list1 != NULL && list2 != NULL)
{
int a = (list1 != NULL) ? list1->data : 0;
int b = (list2 != NULL) ? list2->data : 0;
int sum = carry + a + b;
carry = sum / 10;
cur->next = (Node*)malloc(sizeof(Node));
cur = cur->next;
cur->data = sum % 10;
cur->next = NULL;

if (list1 != NULL)
{
list1 = list1->next;
}
if (list2 != NULL)
{
list2 = list2->next;
}
}
if (carry > 0)
{
cur->next = (Node*)malloc(sizeof(Node));
cur = cur->next;
cur->data = carry;
cur->next = NULL;
}
Node* ret = reverseList(newHead->next);
free(newHead);
return ret;
}

int main() {
LinkedList head1 = NULL;
append(&head1, 1);
append(&head1, 3);
append(&head1, 4);
append(&head1, 6);

LinkedList head2 = NULL;
append(&head2, 1);
append(&head2, 2);
append(&head2, 5);
append(&head2, 8);


LinkedList head = addNodeList(head1, head2);

printf("list :  \n");
printList(head);
system("pause");
return 0;
}

在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_53161762/article/details/137687740

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!