链表面试题练习二
1.删除链表中等于给定值 val 的所有节点
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* newnode=new ListNode(0);
newnode->next=head;
ListNode* pCur=newnode;
while(pCur->next!=nullptr)
{
if(pCur->next->val==val)
{
pCur->next=pCur->next->next;
}
else
pCur=pCur->next;
}
return newnode->next;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre=nullptr;
ListNode *cur=head;
ListNode *next=nullptr;
while(cur!=nullptr){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
3. 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点
//快慢节点做法
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* slow=head;
ListNode* quick=head;
while(quick!=nullptr&&quick->next!=nullptr)
{
slow=slow->next;
quick=quick->next->next;
}
return slow;
}
};
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead == nullptr||k==0)
return nullptr;
ListNode* knode=pListHead;
ListNode* node=pListHead;
for(int i =1;i<k;i++)
{
if(knode->next!=nullptr)
knode=knode->next;
else
return nullptr;
}
while(knode->next!=nullptr)
{
node=node->next;
knode=knode->next;
}
return node;
}
};
5. 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* n1=l1;
ListNode* n2=l2;
ListNode* node=new ListNode(0);
ListNode* end=node;
while(n1&&n2)
{
if(n1->val<n2->val)
{
end->next=n1;
end=end->next;
n1=n1->next;
}
else
{
end->next=n2;
end=end->next;
n2=n2->next;
}
}
//两条链表不能同时为空,必有一条不为空
if(n1!=nullptr)
end->next=n1;
else
end->next=n2;
return node->next;
}
};
6.编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
ListNode *small=new ListNode(0);
ListNode *big=new ListNode(0);
ListNode* small_end=small;
ListNode* big_end=big;
while(pHead){
if(pHead->val<x){
small->next=pHead;
small=small->next;
} else {
big->next=pHead;
big=big->next;
}
pHead=pHead->next;
}
big->next=nullptr;
small->next=big_end->next;
return small_end->next;
}
};
7. 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
ListNode* newHead=new ListNode(0);
newHead->next=pHead;
ListNode* pre=newHead;
ListNode* pnode=pHead;
ListNode* pCur=NULL;
while(pnode!=NULL && pnode->next!=NULL)
{
pCur=pnode->next;
if(pnode->val==pCur->val)
{
while(pCur!=NULL && pCur->val==pnode->val)
pCur=pCur->next;
pre->next=pCur;
pnode=pCur;
}
else
{
pre=pnode;
pnode=pnode->next;
}
}
return newHead->next;
}
};