文章
11
粉丝
223
获赞
14
访问
55.1k
关键点: 1.尾插法建立单链表 2.用两个指针去合并
#include <iostream>
using namespace std;
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int value) : val(value), next(nullptr) {}
};
int main()
{
int S1, S2;
// 两个链表的虚拟头结点
ListNode *phead1 = new ListNode(-1), *phead2 = new ListNode(-1);
// 1.先建立两个链表
ListNode *p, *r;
cin >> S1;
int val;
r = phead1;
for (int i = 0; i < S1; ++i)
{
cin >> val;
ListNode *p = new ListNode(val);
p->next = nullptr;
r->next = p;
r = p;
}
cin >> S2;
r = phead2;
for (int i = 0; i < S2; ++i)
{
cin >> val;
ListNode *p = new ListNode(val);
p->next = nullptr;
r->next = p;
r = p;
}
// 2.合并
ListNode *p1 = phead1->next, *p2 = phead2->next;
ListNode *phead3 = new ListNode(-1), *p3 = phead3;
while (p...
登录后发布评论
暂无评论,来抢沙发