一、判断单链表是否有环
bool IsLinkHasCircle(Node* head,int& val)
{
Node* fast = head;
Node* slow = head;
while (fast != nullptr && fast->next_ != nullptr)
{
slow = slow->next_;
fast = fast->next_->next_;
if (slow == fast)
{
//快慢指针再次遇见,列表存在环
fast = head;
while (fast != slow)
{
slow = slow->next_;
fast = fast->next_;
}
val = slow->data_;
return true;
}
}
return false;
}
二、判断两个链表是否相交(力扣160题)
快慢指针一
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==nullptr||headB==nullptr){
return nullptr;
}
ListNode* p=headA;
ListNode* q=headB;
while(p!=q){
p=p==nullptr?headB:p->next;
q=q==nullptr?headA:q->next;
}
return p;
}
先求长度,让第一个节点先移动长度差
bool IsLinkHasMerge(Node* head1, Node* head2, int& val)
{
int cnt1 = 0, cnt2 = 0;
Node* p = head1->next_;
Node* q = head2->next_;
while (p!=nullptr)
{
cnt1++;
p=p->next_;
}
while (q!=nullptr)
{
cnt2++;
q = q->next_;
}
p = head1->next_;
q = head2->next_;
if (cnt1 > cnt2)
{
//第一个链表长
int offset = cnt1 - cnt2;
while (offset--)
{
p = p->next_;
}
}
else
{
//第二个链表长
int offset = cnt2 - cnt1;
while (offset--)
{
q = q->next_;
}
}
while (p != nullptr && q != nullptr)
{
if (p == q)
{
val = p->data_;
return true;
}
p = p->next_;
q = q->next_;
}
return false;
}
三、删除链表的倒数第N个节点(力扣19题)
C语言
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode h;
h.next=head;
struct ListNode *p=&h;
struct ListNode *q=&h;
while(n--)
{
p=p->next;
}
while(p->next)
{
q=q->next;
p=p->next;
}
q->next=q->next->next;
return h.next;
}
C++
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* root=new ListNode(0,head);
ListNode* end=root;
ListNode* begin=root;
while(n--)
{
end=end->next;
}
while(end->next)
{
end=end->next;
begin=begin->next;
}
begin->next=begin->next->next;
return root->next;
}
四、旋转链表(力扣61题)
ListNode* rotateRight(ListNode* head, int k) {
if(head==nullptr||k==0) return head;
int cnt=0;
ListNode* p=head;
ListNode* q=head;
ListNode* h=head;
while(h)
{
cnt++;
h=h->next;
}
k=k%cnt;
while(k--)
{
p=p->next;
}
while(p->next)
{
p=p->next;
q=q->next;
}
p->next=head;
head=q->next;
q->next=nullptr;
return head;
}
总结
主要就是常见的面试题。