两个有序链表的合并ptac++
时间: 2024-06-12 13:08:39 浏览: 20
两个有序链表的合并可以通过迭代的方式实现。假设有两个有序链表,分别是链表A和链表B。我们可以创建一个新的链表来存储合并后的结果。首先,我们比较链表A和链表B的头结点的值,将较小值的节点添加到新链表中,并将对应链表的指针向后移动一位。然后,再次比较两个链表当前节点的值,直到其中一个链表为空。最后,将非空链表剩余的节点直接添加到新链表的末尾。
以下是一个示例实现的代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_two_lists(l1, l2):
dummy = ListNode(0)
curr = dummy
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if l1:
curr.next = l1
if l2:
curr.next = l2
return dummy.next
```
相关问题
两个有序链表序列的合并pta
将两个有序链表合并成一个链表的方法如下:
1. 创建一个新的链表,将头指针指向NULL。
2. 比较两个链表的当前节点的值,将较小值的节点添加到新链表的尾部,并更新新链表的尾指针。
3. 更新较小值的链表的当前节点为下一个节点。
4. 重复步骤2和步骤3,直到其中一个链表为空。
5. 将另一个非空链表的剩余部分添加到新链表的尾部。
6. 遍历新链表,依次输出合并后的链表的元素值,并计算第奇数位置元素之和。
代码示例:
```
List Merge(List L1, List L2){
List resultList = (List)malloc(sizeof(struct Node));
resultList->Next = NULL;
PtrToNode tail = resultList;
PtrToNode p1 = L1->Next;
PtrToNode p2 = L2->Next;
int sum = 0;
int count = 1;
while(p1 && p2){
if(p1->Data <= p2->Data){
tail->Next = p1;
p1 = p1->Next;
}else{
tail->Next = p2;
p2 = p2->Next;
}
tail = tail->Next;
if(count % 2 == 1){
sum += tail->Data;
}
count++;
}
if(p1){
tail->Next = p1;
}
if(p2){
tail->Next = p2;
}
PtrToNode p = resultList->Next;
while(p){
printf("%d ", p->Data);
p = p->Next;
}
printf("\n");
printf("第奇数位置元素之和:%d\n", sum);
return resultList;
}
```
两个有序链表的合并c
两个有序链表的合并可以通过遍历两个链表,比较节点的值,将较小的值插入到一个新的链表中。具体的实现可以参考下面的示例代码:
```c
#include<stdio.h>
#include<stdlib.h>
// 定义链表节点的结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建一个新的节点
struct ListNode* createNode(int val) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 合并两个有序链表
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
// 创建一个新的链表头节点
struct ListNode* dummyNode = createNode(0);
struct ListNode* current = dummyNode;
// 遍历两个链表
while (l1 != NULL && l2 != NULL) {
// 比较节点的值,将较小的节点插入到新链表中
if (l1->val <= l2->val) {
current->next = l1;
l1 = l1->next;
} else {
current->next = l2;
l2 = l2->next;
}
current = current->next;
}
// 将剩余的节点插入到新链表中
if (l1 != NULL) {
current->next = l1;
}
if (l2 != NULL) {
current->next = l2;
}
return dummyNode->next;
}
// 打印链表
void printList(struct ListNode* head) {
struct ListNode* current = head;
while (current != NULL) {
printf("%d ", current->val);
current = current->next;
}
printf("\n");
}
int main() {
// 创建两个有序链表
struct ListNode* l1 = createNode(1);
l1->next = createNode(2);
l1->next->next = createNode(4);
struct ListNode* l2 = createNode(1);
l2->next = createNode(3);
l2->next->next = createNode(4);
// 合并两个链表
struct ListNode* mergedList = mergeTwoLists(l1, l2);
// 打印合并后的链表
printList(mergedList);
// 释放链表的内存
struct ListNode* current = mergedList;
while (current != NULL) {
struct ListNode* temp = current;
current = current->next;
free(temp);
}
return 0;
}
```