BM3 链表中的节点每k个一组翻转
class Solution{
public:
ListNode* revers(ListNode* tail,ListNode* head){
if(head==tail) return head;
ListNode* pre=nullptr;
ListNode* cur=head;
while(cur!=tail){
ListNode* next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
ListNode* reverseGroup(ListNode* head,int k){
if(!head) return head;
ListNode* tail=head;
for(int i=0;i<k;i++){
if(!tail) return head;
tail=tail->next;
}
ListNode* newHead=revers(head,tail);
head->next=reverseGroup(tail,k);
return newHead;
}
}
BM4 合并两个排序链表
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode* L=new ListNode(0);
ListNode* s=L;
while(pHead1!=nullptr&&pHead2!=nullptr){
if(pHead1->val<pHead2->val){
s->next=pHead1;
s=s->next;
pHead1=pHead1->next;
}
else{
s->next=pHead2;
s=s->next;
pHead2=pHead2->next;
}
}
if(pHead1==nullptr){
s->next=pHead2;
}
else{
s->next=pHead1;
}
return L->next;
}
};
BM6 判断链表中是否有环
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> seen;
while(head!=nullptr){
if(seen.count(head)){//返回匹配主键元素的个数
return true;
}
seen.insert(head);
head=head->next;
}
return false;
}
};
BM7 链表中环的入口节点
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
unordered_set<ListNode*> seen;
while(pHead!=nullptr){
if(seen.count(pHead)){
return pHead;
}
seen.insert(pHead);
pHead=pHead->next;
}
return nullptr;
}
};
BM8 立案表中倒数最后k个结点
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
if(!pHead) return pHead;
ListNode* first=pHead;
ListNode* second=pHead;
while(k-->0){
if(first==nullptr){
return nullptr;
}
first=first->next;
}
while(first!=nullptr){
first=first->next;
second=second->next;
}
return second;
}
};
BM9 删除链表的倒数第n个结点
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
if(!head) return head;
ListNode* first=head;
ListNode* seconde=head;
while(n-->0){
first=first->next;
}
if(first==nullptr)
return head->next;
while(first->next){
first=first->next;
seconde=seconde->next;
}
seconde->next=seconde->next->next;
return head;
}
};
BM10 两个链表的第一个公共结点
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
unordered_set<ListNode*> seen;
while(pHead1!=nullptr){
seen.insert(pHead1);
pHead1=pHead1->next;
}
while(pHead2!=nullptr){
if(seen.count(pHead2)){
return pHead2;
}
pHead2=pHead2->next;
}
return nullptr;
}
};
- 本文链接:https://archer-lan.github.io/2022/03/16/%E7%89%9B%E5%AE%A2%E5%88%B7%E9%A2%98-DAY2/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。