您的位置:首页 > 理论基础 > 数据结构算法

【数据结构_链表_最小堆】 链表找环,链表找交点,合并有序链表

2014-08-02 21:27 288 查看

Linked List Cycle

Given a linked list, determine if it has a cycle in it.
Follow up:

Can you solve it without using extra space?

对链表反序: while(p) { q=p->next; p->next=f; f=p;p=q;}

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *p=head,*q,*f=NULL;
while(p){//对链表反序,如果p回到起点,则有环
q=p->next;
p->next=f;
f=p;p=q;
if(p==head) return true;//有环
}
return false;//沒有环,p到了NULL
}
};

合并有序链表

用优先队列(小顶堆)

class Solution {
public:
struct cmp{
bool operator () ( const pair<int, int> &a, const pair<int, int > &b){
return a.first >= b.first;
}
}cc;
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<pair<int, int>, vector<pair<int, int> >, cmp> que;
for(int i=0; i<lists.size(); i++) if(lists[i])
que.push(pair<int, int>(lists[i]->val, i));

ListNode *head =NULL, *tail =NULL;
while(!que.empty()){
pair<int, int> t = que.top(); que.pop();
int i = t.second;
if(!head) head = lists[i];
else tail -> next = lists[i];
tail = lists[i];
lists[i] = lists[i]->next;
if(lists[i])
que.push(pair<int, int>(lists[i]->val, i));
}

if(tail) tail->next = NULL;

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: