〇、目录
一、反转链表
1、简单版:反转全部节点
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* newhead=NULL;
while(head)
{
ListNode* nex=head->next;
head->next=newhead;
newhead=head;
head=nex;
}
return newhead;
}
};
2、进阶版:从指定节点到指定节点反转
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
int change_len=n-m+1;
ListNode* pre_head=NULL;
ListNode* result=head;
while(head && --m)
{
pre_head=head;
head=head->next;
}
ListNode* modify_list_tail=head;
ListNode* newnode=NULL;
while(head && change_len)
{
ListNode* nex=head->next;
head->next=newnode;
newnode=head;
head=nex;
change_len--;
}
modify_list_tail->next=head;
if(pre_head)
{
pre_head->next=newnode;
}
else
{
result=newnode;
}
return result;
}
};
二、求两个链表的交点
法一、使用STL——set
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
std::set<ListNode*> node_set;
while(headA)
{
node_set.insert(headA);
headA=headA->next;
}
while(headB)
{
if(node_set.find(headB)!=node_set.end())
{
return headB;
}
headB=headB->next;
}
return NULL;
}
};
法二、双指针
class Solution {
public:
int len(ListNode* node)
{
int length=0;
while(node)
{
node=node->next;
length++;
}
return length;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* longnode;
ListNode* shortnode;
int dis=0;
int len1=len(headA);
int len2=len(headB);
if(len1>len2)
{
longnode=headA;
shortnode=headB;
dis=len1-len2;
}
else
{
longnode=headB;
shortnode=headA;
dis=len2-len1;
}
while(dis)
{
longnode=longnode->next;
dis--;
}
while(longnode && shortnode && longnode!=shortnode)
{
longnode=longnode->next;
shortnode=shortnode->next;
}
return longnode;
}
};
三、链表求环
1、简单版:判断链表是否有环
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast=head;
ListNode* slow=head;
if(head==NULL)
{
return false;
}
while(fast && fast->next)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
return true;
}
}
return false;
}
};
2、进阶版:找出环的起始节点
法一、使用STL—set
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
std::set<ListNode*> node_set;
while(head)
{
if(node_set.find(head)!=node_set.end())
{
return head;
}
node_set.insert(head);
head=head->next;
}
return NULL;
}
};
法二、快慢指针
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast=head;
ListNode* slow=head;
ListNode* meet=NULL;
if(!head)
{
return NULL;
}
while(fast && fast->next)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
meet=fast;
break;
}
}
if(meet==NULL)
{
return NULL;
}
while(head && meet)
{
if(head==meet)
{
return head;
}
head=head->next;
meet=meet->next;
}
return NULL;
}
};
四、链表划分
使用临时头节点:
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode less_head(0);
ListNode more_head(0);
ListNode* less_ptr=&less_head;
ListNode* more_ptr=&more_head;
while(head)
{
if(head->val < x)
{
less_ptr->next=head;
less_ptr=head;
}
else
{
more_ptr->next=head;
more_ptr=head;
}
head=head->next;
}
less_ptr->next=more_head.next;
more_ptr->next=NULL;
return less_head.next;
}
};