版权声明:引用请加上链接,欢迎评论 https://blog.csdn.net/weixin_40457801/article/details/89792179
1、两个有序链表合并
在leetcode上遇到的题目,老生常谈题目,这里使用c++实现,数据结构书里有这种题的。我一直用的这种遍历比较,然后接入到第三个链表里这种方法。还有递归方法和遍历不创建新链表的方法,这里就不赘述了
定义结构体
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}//实现初始化
};
代码块
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
//保持代码健壮性
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
//新建链表3,存放
ListNode* l3=new ListNode(0);
ListNode* p=l3;
while (l1!= NULL&&l2!=NULL) {
if (l1->val<=l2->val)
{
p->next=l1;
l1=l1->next;
}
else
{
p->next=l2;
l2=l2->next;
}
p = p->next;
}
p->next=(l1!=NULL)?l1:l2;//接入未完链表
return l3->next;//去表头
}
};
2、找到链表倒数第k个节点
注释都很清楚了,我就不多说了,代码都挺简单的
#include <iostream>
#include <stack>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, int k) {
if (pListHead == NULL || k <= 0)
//因为是无符号,所以要加k<=0判断
return NULL;
ListNode* fast = pListHead;
ListNode* slow = pListHead;
//思路快指针先走k-1,然后快慢一起走,当快指向null的前一个即最后一个点时,慢指针指向倒数k
for (int i = 0; i<k; i++)
{
if (fast == NULL) return NULL;
//会出现k大过链表长度,所以这里要加判断
fast = fast->next;
}
while (fast != NULL)
{
fast = fast->next;
slow = slow->next;
}
return slow;
}
//相较于上,有点不好,时间复杂度O(2n),还开辟了空间复杂度,就相当于加强实现能力吧
//思路 使用栈的思想实现倒序
ListNode* FindKthToTail_stack(ListNode* pListHead, int k) {
if (pListHead == NULL || k <= 0) return NULL;
stack<ListNode*> s;
ListNode* p = pListHead;
while (p != NULL)
{
s.push(p);
p = p->next;
}
for (int i = 0; i<k - 1; i++)
{
s.pop();
if (s.empty())
return NULL;
}
return s.top();
}
void creatList(ListNode* head, int n)
{
ListNode* p = head;
ListNode* r = head;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
p = new ListNode(x);
r->next = p;
r = p;
}
r->next = NULL;
}
};
int main()
{
Solution so;
ListNode* pListHead1=new ListNode( NULL);
ListNode* res;
so.creatList(pListHead1, 6);//建立5个节点
res = so.FindKthToTail_stack(pListHead1, 3);//stack实现倒数第三个
int a = res->val;
cout << "stack实现" << endl;
cout << a << endl;
res = so.FindKthToTail(pListHead1, 3);//倒数第三个
int b = res->val;
cout << "最优" << endl;
cout << b << endl;
}