链表的常见相关操作
链表的反转 两种方式递归非递归
#include <iostream>
struct node
{
int data;
struct node *next;
};
typedef struct node LIST;
//循环的链表的反转
LIST * reverseList(LIST *phead)
{
LIST *pnow = phead;
LIST *ppre = NULL;
LIST *pnext = NULL;
LIST *newhead = NULL;
while(pnow != NULL)
{
pnext = pnow->next;//1.pnext指向当前节点的下一个节点
if(pnext == NULL)
{
newhead = pnow;
}
pnow->next=ppre;//2.把当前节点的连接断开,指向前一个节点ppre
ppre = pnow;//3.更新前一个节点,指向当前节点
pnow = pnext;//4.更新现在的节点,指向下一个节点
}
return newhead;
}
//递归的链表反转
LIST *reverseList2(LIST *phead)
{
LIST *current = phead;
//检测链表为空,或者已经检测到尾节点时,满足种植条件,停止向下递归
if(current == NULL|| current->next == NULL)
{
return current;
}
//执行递归操作,寻找尾节点
LIST *newhead = reverseList2(current->next);
//反转操作,目的是完成当前节点的下一个节点,完成指向当前节点的操作
current->next->next = current;
//该语句很重要,不执行会使链表大乱
current->next = NULL;
return newhead;
}
找到链表的中点(快慢指针)
//找到链表的中点,快慢指针
LIST *findmid(LIST *head)
{
LIST* slow = head;
LIST* fast = head;
while(fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
交叉合并两个链表
//交叉合并两个链表
void combine(LIST *head, LIST *pre)
{
while(head!= NULL&& pre!= NULL)
{
LIST *nxt=head->next;
head->next = pre;
pre=pre->next;
head->next->next=nxt;
head=nxt;
}
}
判断链表是否有环
//判断链表是否有环
/*首先,slow指针和fast指针都会进入环内,就像在环形跑道内不同位置的两个人。slow指针在后面,fast指针在前面,但实际上fast指针也在追slow指针,希望能超slow指针一圈。那么fast指针总会追上slow指针的。那么fast指针会不会跳过slow指针呢?不会的,因为fast每次走2步,slow每次走1步,假设两者在环内的距离差为N,那么每次走动,距离差N都会缩小一步,因为fast与slow指针的步长差是1。最终,N会减少到0,也就是两者会相遇。
*/
bool hasCircle(LIST *head)
{
LIST * slow = head;
LIST * fast = head;
while(fast!=NULL&&fast->next!=NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow==fast) return true;
}
return false;
}
返回链表环的入口节点
先用快慢指针判断是否有环,若有环,在两个指针的相遇处,让快指针指向头,然后快慢指针此时每次走一步,两个指针的再次相遇的节点就是环的入口节点。
/返回链表中环的入口节点
ListNode * EntryNodeOfLoop(ListNode *phead)
{
if(phead==NULL || phead->next == NULL)
{
return nullptr;
}
ListNode * slow = phead;
ListNode * fast = phead;
while (fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
fast = phead;
while(fast!=slow)
{
fast = fast->next;
slow = slow->next;
}
if (fast == slow)
{
return slow;
}
}
}
return nullptr;
}
合并两个有序链表
//合并两个有序链表
ListNode* mergeTwoLists(ListNode * l1, ListNode *l2)
{
ListNode *head = new ListNode(0);//哨兵节点
ListNode *temp = head;
//依次比较两个链表的节点,将值较小的节点插入到新建的链表后面
while(l1 && l2)
{
if(l1->val<=l2->val)
{
temp->next = l2;
temp = temp->next;
l2 = l2->next;
}
else
{
temp->next = l1;
temp = temp->next;
l1 = l1->next;
}
}
//其中一个链表到达了结尾,把另一个链表剩下的节点直接插入到新建的链表后面
if(l1)
{
temp->next = l1;
}
else
{
temp->next = l2;
}
temp = head;
head = head->next;
delete(temp);
return head;
}