c++刷题(9100):链表
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
c++刷题(9100):链表
题⽬⼀:https:///practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题⽬描述
输⼊⼀个链表,从尾到头打印链表每个节点的值。
思路:之前看到书上两个链表相加然后(从tail开始)就发现这种从尾部开始的情况都可以⽤栈来实现,很容易理解,这题也⼀样
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> list ;
stack<int> s ;
while(head!=NULL){
s.push(head->val) ;
head = head->next ;
}
while(!s.empty()){
list.push_back(s.top()) ;
s.pop() ;
}
return list ;
}
};
题⽬⼆:
在⼀个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:如果保留重复的节点就很简单,不保留的话,每次向后遍历删完节点之后还要把之前的第⼀个节点删了,需要判断⼀下,如果被删的是头节点,还要判断⼀下。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead==NULL) {return NULL;}
set<int> s ;
ListNode* cur = pHead ;
ListNode* pre = pHead ;
ListNode* check ;
ListNode* checkpre ;
bool firstTodel ;
while(cur!=NULL){
int temp = cur->val ;
check = cur->next ;
checkpre = cur ;
firstTodel = false ;
while(check!=NULL){
if(check->val==temp){
checkpre->next = check->next ;
firstTodel = true ;
}else{
checkpre = check ;
}
check = check->next ;
}
if(firstTodel){
if(cur==pHead){
pHead = pHead->next ;
pre = pre->next ;
}else{
pre->next = cur->next ;
}
}else{
pre = cur ;
}
cur = cur->next ;
}
return pHead ;
}
};
题⽬三:
题⽬描述
⼀个链表中包含环,请找出该链表的环的⼊⼝结点。
思路:⼀开始想到set,后⾯觉得不⾏,因为可能会有两个⼀样的node,然后百度知道了双指针的⽅法。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode* fast ;
ListNode* slow ;
fast = pHead ;
slow = pHead ;
if(fast==NULL){
return NULL ;
}
while(fast!=NULL&&fast->next!=NULL){
fast = fast->next->next ;
slow = slow->next ;
if(fast==slow){
fast = pHead ;
while(fast!=slow){
fast = fast->next ;
slow = slow->next ;
}
return fast ;
}
}
return NULL ;
}
};
链表的总结:
有翻转性质的可以⽤栈,删除要记录前⼀个Node。