写一个代码,包含建立单链表,查找单链表,插入单链表,删除单链表,并且采用单链表结构编程实现两个有序单链表的归并运算
时间: 2024-03-23 21:24:34 浏览: 63
//定义单链表的结构体
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//建立单链表
ListNode* createLinkedList(vector<int> nums) {
ListNode* head = new ListNode(0);
ListNode* p = head;
for (int i = 0; i < nums.size(); i++) {
p->next = new ListNode(nums[i]);
p = p->next;
}
return head->next;
}
//查找单链表,返回找到的节点
ListNode* searchLinkedList(ListNode* head, int val) {
ListNode* p = head;
while (p != NULL && p->val != val) {
p = p->next;
}
return p;
}
//插入单链表,在节点后插入
void insertLinkedList(ListNode* node, int val) {
ListNode* p = new ListNode(val);
p->next = node->next;
node->next = p;
}
//删除单链表,删除节点
void deleteLinkedList(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
//归并两个有序单链表,返回合并后的链表
ListNode* mergeLinkedList(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(0);
ListNode* p = head;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
p->next = l1;
l1 = l1->next;
} else {
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if (l1 != NULL) {
p->next = l1;
} else {
p->next = l2;
}
return head->next;
}
阅读全文