单向链表
单向链表的创建
#pragma once
#include<initializer_list>
#include<iostream>
#ifndef _LISTNODE_H
struct ListNode
{
int value
;
ListNode
* next
;
ListNode() :value(0), next(nullptr) {}
ListNode(int x
) :value(x
), next(nullptr) {}
ListNode(int x
, ListNode
* next1
) :value(x
), next(next1
) {}
public:
void printList(const ListNode
* out
);
void releaseListNode(ListNode
* l
);
void free(ListNode
* node
);
};
void ListNode
::releaseListNode(ListNode
* node
)
{
ListNode
* temp
;
for (auto start
= node
; start
!= nullptr; start
= start
->next
)
{
temp
= start
->next
;
}
}
void
ListNode
::free(ListNode
* node
)
{
delete node
->next
;
}
ListNode
initList(const std
::initializer_list
<int>& init
);
ListNode
initList(const std
::initializer_list
<int>& init
)
{
ListNode
*result
= nullptr;
ListNode
** node
= &result
;
for (auto iter
= init
.begin(); iter
!= init
.end(); ++iter
)
{
*node
= new ListNode(*iter
);
node
= &((*node
)->next
);
}
return *result
;
}
void
ListNode
::printList(const ListNode
* out
)
{
for (auto start
= out
; start
!= nullptr; start
= start
->next
)
std
::cout
<< start
->value
<<" ";
std
::cout
<< std
::endl
;
}
ListNode
addTwoNumber(ListNode
* l1
, ListNode
* l2
);
ListNode
addTwoNumber(ListNode
* l1
, ListNode
* l2
)
{
int sum
= 0;
ListNode
* l3
= nullptr;
ListNode
** node
= &l3
;
while (l1
!= nullptr || l2
!= nullptr || sum
> 0)
{
if (l1
!= nullptr)
{
sum
+= l1
->value
;
l1
= l1
->next
;
}
if (l2
!= nullptr)
{
sum
+= l2
->value
;
l2
= l2
->next
;
}
*node
= new ListNode(sum
% 10);
sum
/= 10;
node
= &((*node
)->next
);
}
return *l3
;
}
#endif
#include<cstdlib>
#include"ListNode.h"
#include<iostream>
int main()
{
std
::cout
<< "Hello World" << std
::endl
;
ListNode l1
; ListNode l2
;
l1
= initList({ 2,4,3 });
l2
= initList({ 5,6,4 });
ListNode result
;
result
=addTwoNumber(&l1
,&l2
);
l1
.printList(&l1
);
l1
.printList(&l2
);
l1
.printList(&result
);
system("pause");
}
测试结果
转载请注明原文地址:https://blackberry.8miu.com/read-26630.html