#每日一题2018/3/28

本文解析了LeetCode上的三道经典链表题目:合并K个有序链表、交换链表相邻元素值及反转每K个节点。通过代码示例详细介绍了如何使用优先队列、递归等方法解决这些挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode 23

合并k个有序链表,维护一个最小堆,堆由每一个链表的第一个元素组成,每次取堆顶元素,之后用该链表结点的next结点来替换。用优先队列实现最小堆

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	struct cmp{
		bool operator()(const ListNode* a,const ListNode* b)
		{
			return a->val>b->val;
		}
	};
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int length=lists.size();
        if(length==0) return NULL;
        ListNode node(0),*res=&node;
        priority_queue<ListNode*,vector<ListNode*>,cmp> queue;
        for(int i=0;i<length;i++)
		{
			if(lists[i])
			{
				queue.push(lists[i]);
			}
		}
		while(!queue.empty())
		{
			ListNode* p=queue.top();
			queue.pop();
			res->next=p;
			res=p;
			if(p->next)
			{
				queue.push(p->next);	
			}	
		}
		return node.next;
    }
};
leetcode 24

交换链表相邻元素值

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        int first;
        ListNode* phead=head;
        while(head!=NULL&&head->next!=NULL)
        {
        	first=head->val;
        	head->val=head->next->val;
        	head->next->val=first;
        	head=head->next->next;
		}
		return phead;
    }
};

leetcode 25

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
    	if(head==NULL)
		{
			return NULL;
		}
		ListNode* fake=new ListNode(0);
		fake->next=head; 
		ListNode* l=head;
		int count=0;
		while(l!=NULL)
		{
			count++;
			l=l->next;
		}
		if(k>count) return head;
		ListNode* after=NULL;
		l=head;
		ListNode* pre=l->next;
		for(int i=0;i<k;i++)
		{
			fake->next=l;
			l->next=after;
			after=l;
			l=pre;
			if(pre!=NULL) pre=pre->next;
		}
		head->next=reverseKGroup(l,k);
		return fake->next;
    }
};
写这道题的时候我真的很困……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值