一、单链表逆序
力扣无头链表
ListNode* reverseList(ListNode* head) {
ListNode* p=nullptr;
ListNode* q=head;
while(q)
{
ListNode* next=q->next;
q->next=p;
p=q;
q=next;
}
return p;
}
有头链表(采用头插法)
void ReverseLink(Clink& link)
{
Node* p = link.head_->next_;
if (p == nullptr)
{
return;
}
link.head_->next_ = nullptr;
while (p != nullptr)
{
Node* q = p->next_;
//p指针指向的节点进行头插
p->next_ = link.head_->next_;
link.head_->next_ = p;
p = q;
}
}
二、求倒数第k个节点的值
力扣无头节点
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode* p=head;
ListNode* q=head;
for(int i=1;i<k;i++)
{
p=p->next;
}
while(p->next!=nullptr){
p=p->next;
q=q->next;
}
return q;
}
有头节点
bool GetLastKNode(Clink& link, int k, int& val)
{
Node* head = link.head_;
Node* p = head;
Node* pre = head;
if (k < 1)
{
return false;
}
while (k--)
{
p = p->next_;
if (p == nullptr)
{
return false;
}
}
//pre在头节点,p在整数第k个节点
while (p != nullptr)
{
p = p->next_;
pre = pre->next_;
}
val = pre->data_;
return true;
}
三、合并两个有序链表
力扣无头链表
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* p=l1;
ListNode* q=l2;
ListNode* head=new ListNode(0);
ListNode* last=head;
while(p!=nullptr&&q!=nullptr)
{
if(p->val<q->val)
{
last->next=p;
p=p->next;
last=last->next;
}
else
{
last->next=q;
q=q->next;
last=last->next;
}
}
if(p!=nullptr)
{
last->next=p;
}
else{
last->next=q;
}
return head->next;
}
有头链表
void MergeLink(Clink& link1, Clink& link2)
{
Node* last = link1.head_;
Node* p = link1.head_->next_;
Node* q = link2.head_->next_;
//link2.head_ = nullptr;
while (p != nullptr && q != nullptr)
{
if (p->data_ < q->data_)
{
last->next_ = p;
p = p->next_;
last = last->next_;
}
else
{
last->next_ = q;
q = q->next_;
last = last->next_;
}
}
if (p != nullptr)
{
last->next_ = p;
}
else
{
last->next_ = q;
}
}
总结
今天主要给大家介绍了单链表的一些面试题,力扣主要以无头链表的形式出现,所以我又列出来有头链表的实现。