刷题 - 数据结构(二)链表

1. 链表

1.1 题目:合并两个有序链表

  1. 链表的建立与插入:关键在于留出头部,创建迭代指针。
    ListNode* head = new ListNode; // 通过new 创建了一个数据类型为ListNode的数据 并把该数据的地址赋值给ListNode
    ListNode* p = 0; // 再创建一个数据类型为ListNode的数据 并把该数据的地址赋值给ListNode
    p = head; // 把head 里面的地址赋值给p

完整的代码


作者:小陈写不完代码
链接:https://zhuanlan.zhihu.com/p/365219765
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

#include<iostream>
#include<string>
using namespace std;
struct node
{
    string name;
    int score;
    node* next;
};
node* creatList(); // 创建了一个返回值为指向数据类型为node的执政,即返回的是一个地址
int main()
{
    node* head=creatList();
}
node* creatList()
{
    node* head = new node; // 通过new 创建了一个数据类型为node的数据 并把该数据的地址赋值给node
    node* p= new node; // 再创建一个数据类型为node的数据 并把该数据的地址赋值给node
    p=head; // 把head 里面的地址赋值给p
    p->next=NULL; //这里把p指向的数据类型为node的数据里的 指针next指向了空.指针必须有对象 即指向一个地方,你不告诉它 它就乱跑 所以一般都是让它空着
    while (true) // 这里我选择while循环 因为里面是true 所以会一直进行 ,我们在里面使用条件判断加break跳出来
    {
        cout<<"Please enter student name: ";
        cin>>p->name; // 录入学生的姓名
        cout<<"Please enter student score: ";
        cin>>p->score; // 输入学生的分数
        if(p->score <0){
            break; // 如果分数小于0 跳出循环即输入结束.
        }
        node*q =new node; // 没有跳出循环 即继续输入,这时我们再创建一个这些数据类型为node的数据 并把它的地址赋值给 指针变量 q .
        p->next=q; // 刚刚p指针指向的数据类型为node的数据里的 指针next 指向 q ,节点p 和 节点q连起来了..
        q->next=NULL; // 指针q指向的数据类型为node的数据里的指针 next 指针也不能乱指,所以我们让它指向 NULL
        p=q; // 这里我当初就搞了很长时间.还记的嘛 p 和 q 是什么 ,它们两都是指针变量.它们里面放的是地址,而且它们里面的地址是可以给其它的指向相同数据类型的指针的,这里我们把q里面的地址 给了p 这样p里面存放的地址就是这个链表的最后一个节点的地址.如此反复我们就实现了动态输入.
    }
    return head; // 这就是为什么我们要设置head了,因为p的地址是不断变化的,而head里面的地址是不变的.而且head里面放的就是第一个节点的地址,
}

或者

// 链表的创建
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
struct ListNode
{
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {};
};
void addToTail(ListNode** head, int val)
{
    ListNode* node = new ListNode(val);
    if (!*head)
    {
        *head = node;
    }
    else
    {
        ListNode* tmp = *head;
        while (tmp->next)
            tmp = tmp->next;
        tmp->next = node;
    }

}

void printList(ListNode* head)
{
    ListNode* tmp;
    tmp = head;
    if (tmp == NULL)
        cout << "empty list";
    else
    {
        while (tmp != NULL)
        {
            cout << tmp->val << ',';
            tmp = tmp->next;
        }
        cout << endl;
    }
}

void addToPos(ListNode** head, int pos_val, int insert_val)
{
    ListNode* curr = *head;
    while (curr) {
        if (curr->val == pos_val) {
            ListNode* new_node = new ListNode(insert_val);
            new_node->next = curr->next;
            curr->next = new_node;
            return;
        }
        curr = curr->next;
    }
}
 
int main()
{
    int lt = time(NULL);
    srand(lt);
    int len = 1;
    int a[] = { 1,2,4 };
    int a2[] = { 1,3,4 };
    ListNode* root2 = NULL;

    ListNode* root1 = NULL;  ListNode* root3 = 0;
    for (auto i:a)
        addToTail(&root1,i);
    for (auto i : a2)
        addToTail(&root2, i);
 
}
 
  1. 依据数组创建列表的时候,需要考虑到:函数内部不好获得数组的长度。sizeof 的方法卸载main中可以,但是对于函数的形参指针就不行了。
    解决方法:类模板+引用。
template<class T>
void arr(T &a)
{
	int n = sizeof(a) / sizeof(a[0]);
	cout << n << endl;
}
 
int main()
{
	int a[] = { 6,-1,3,-4,-6,9,2,-2,5 };
	arr(a);
}
  1. 总结:其实就是:确定指向(pre->next = ),激活当前(pre = pre->next)
  2. 总代码:
 
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(0);    记录一下头的位置
        ListNode* cur = dummy;                            弄个哨兵变量用于遍历
        while (l1 != nullptr && l2 != nullptr) {
            ListNode** pp = (l1->val < l2->val) ? &l1 : &l2;
            cur->next = *pp;
            cur = cur->next;
            *pp = (*pp)->next;
        }
        cur->next = (l1 == nullptr) ? l2 : l1;

        ListNode* ans = dummy->next;
        delete dummy;
        return ans;
    }

2023年2月23日 更新这个题目

今天又遇到。

  1. 能否在节点调节指针走向?
    应该不行。分析后发现,这个思路依据 “当前指向next < 对面的值”,你这个对面的值怎么表达?
  2. 为什么要用指针的指针?
    是这样的,你一会要更新l1, 一会是 l2,这就需要用到指针的指针。

下面是我的代码,犯了几个错误。
1 . 关心下一个而不是本体导致了循环的思路不清晰;


ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    ListNode* temp1 = list1;
    ListNode* temp2 = list2;
    ListNode* dummy = new ListNode(0);
    ListNode* cur = dummy;
    if (list2->val <= list1->val)
    {
        dummy->next = list2;
        cur = list2;
    }
    else
    {
        dummy->next = list1;
        cur = list1;
    }
    while((list1)&& (list2))
    { 
        if (cur->next->val <= list1->next->val)
        {
            temp2 = temp2->next;
            list2->next = list1;     
            list2 = temp2;
        }
        else
        {
            temp1 = temp1->next;
            list1->next = list2;
            list1 = temp1;
        }
    }
    return dummy->next;
}

修改后

ListNode* mergeTwoLists(ListNode * l1, ListNode * l2) {
    ListNode* dummy = new ListNode(0);    //记录一下头的位置
        ListNode* cur = dummy;
        while (l1 != nullptr && l2 != nullptr)
        {       
            if (l1->val < l2->val)
            {
                cur->next = l1;
                cur = cur->next;
                l1 = l1->next;
            }
            else
            {
                cur->next = l2;
                cur = cur->next;
                l2 = l2->next;
            }
}
    cur->next = (l1 == nullptr) ? l2 : l1;
    ListNode* ans = dummy->next;
    delete dummy;
    return ans;
}

2. 删除排序链表中的重复元素

// 原来的代码有错误
ListNode* deleteDuplicates(ListNode* head) {   
    ListNode* new_head = new ListNode(head->val);
    ListNode* h = new_head;
    int temp = head->val;
    head = head->next;
    while (head != nullptr) {
        if (head->val != temp) {
            h->next = head;
            h = h->next;
        }


        temp = head->val;
        head = head->next;
    }
    return new_head;
}

修改了

ListNode* deleteDuplicates(ListNode* head) {
           if (!head) {
            return head;
        }
    ListNode* new_head = new ListNode(head->val);
    ListNode* h = new_head;
    int temp = head->val;
    head = head->next;
    while (head != nullptr) {
        if (head->val != temp) {
            h->next = head;
            h = h->next;
            temp = head->val;
            head = head->next;
        }
        else {
            temp = head->val;
            head = head->next;
            h->next = head; // 这句话一定要,他不是定义,他是修改!!!
        }
        
    }
    return new_head;
}


题目四、 删除链表的倒数第 N 个结点

开始的想法:

  1. 必须获得链表长度;(后面发现不一定)
  2. 循环到某个的时候跳过就好
    但是发现还少了一些
  3. 必须要用哑结点(头节点要一视同仁);

下面是我的代码,没用到哑结点,要不断排除特殊情况。

    ListNode* removeNthFromEnd(ListNode* head, int n) {
    int n1 = 0;
    ListNode* cur = head;
    while (cur != nullptr) {
        ++n1;
        cur = cur->next;
    }
    if (n1 ==1) return head->next;  // 啰嗦了,但是必要的
    int k = 0;
    cur = head;
    if (k > n1 - n -1) return head->next;
    while (k < n1 - n -1) {
        ++k;
        cur = cur->next;
    }
    cur->next = cur->next->next;
    return head;
    }

把上面的代码稍微修改,加入哑结点就好。

class Solution {
public:
    int getLength(ListNode* head) {
        int length = 0;
        while (head) {
            ++length;
            head = head->next;
        }
        return length;
    }

    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy = new ListNode(0, head);
        int length = getLength(head);
        ListNode* cur = dummy;
        for (int i = 1; i < length - n + 1; ++i) {
            cur = cur->next;
        }
        cur->next = cur->next->next;
        ListNode* ans = dummy->next;
        delete dummy;
        return ans;
    }
};

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

当然,双指针发可以避免获取总长度

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy = new ListNode(0, head);
        ListNode* first = head;
        ListNode* second = dummy;
        for (int i = 0; i < n; ++i) {
            first = first->next;
        }
        while (first) {
            first = first->next;
            second = second->next;
        }
        second->next = second->next->next;
        ListNode* ans = dummy->next;
        delete dummy;
        return ans;
    }
};

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

2023年9月27日 复习

  • 问题:
    1. 链表传参数为什么要用双指针?
      • 这个就是指针传递和值传递的区别,如果双指针就不用返回 head,否则要记录一下head 用于返回 。一个返回void类型,一个返回Node类型
    2. 为什么链表要用指针?
      因为循环变量会不断更新,不断调用构造函数。用指针可以避免。
    3. 手撕:反转链表
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值