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;
}
};
写这道题的时候我真的很困……