链表的几个相关操作

这篇文章用来总结有通用性的代码参考,以后会不定时更新

链表的定义

typedef struct myNode inode;
struct myNode{
    inode* next;
    int   data;
};

生成链表

注意一点:为了操作方便,设置了一个空的头结点

/************************************
生成一个链表,并且返回头结点
(数组的大小不能小于n,否则会越界)
*************************************/
inode* list_init(int a[], int n){

    inode*head = new inode();
    inode*current = head;
    for (int i = 0; i < n; i++){
        inode* nn = new inode();
        nn->data = a[i];
        current->next = nn;
        current = nn;
    }
    return head;
}

删除链表中的重复元素

/*基本思想是用一个map来记录之前遍历过的链表元素,如果当前元素存在于其中,则删除之*/
#include<map>
void removeDuplicate(inode* head){
    if (head == NULL)
        return;
    map<int, bool> mapcount;
    inode* p = head;
    inode*  q = head->next;
    /*遍历对象是q,p是为了保留其前一个结点*/
    while (q != NULL){
        if (mapcount[q->data]){
            inode* temp = q;
            p->next = q->next;
            q = q->next;
            delete temp;
        }
        else{
            mapcount[q->data] = true;
            p = q;
            q = q->next;
        }
    }
}

两个链表的相加

你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的, 也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。


inode* add_list(inode* left_head, inode* right_head){
    inode* p = left_head->next;
    inode* q = right_head->next;
    int c = 0;
    inode* res_head = new inode();
    inode*  current = res_head;
    while (p && q){
        inode*  nn = new inode();
        int t = p->data + q->data + c;
        nn->data =t%10;
        c = t/ 10;
        current->next = nn;
        current = nn;
        p = p->next;
        q = q->next;
    }
    while (q){
        inode* nn = new inode();
        int t = q->data + c;
        nn->data = t%10;
        c = t / 10;
        current->next = nn;
        current = nn;
        q = q->next;
    }
    while (p){
        inode* nn = new inode();
        int t = p->data + c;
        nn->data =t%10;
        c = t / 10;
        current->next = nn;
        current = nn;
        p=p ->next;
    }
    if (c){
        inode* nn = new inode();
        nn->data = c;
        current->next = nn;
        current = nn;
    }
    return res_head;
}

寻找环的开始位置

循环链表:链表中一个结点的指针指向先前已经出现的结点,导致链表中出现环。

例子:

输入:A -> B -> C -> D -> E -> C [结点C在之前已经出现过]

//思路:使用一个map数组来记录已经遍历过的结点(地址),如果发现这个结点已经遍历过,则返回
inode* loop_start(inode* head){
    inode* p = head->next;
    map<inode*, bool> map_node;
    while (p){
        if (map_node[p])
            return p;
        map_node[p] = true;
        p = p->next;
    }
}

版权声明:本文为博主原创文章,转载请标明出处。

转载于:https://www.cnblogs.com/fridge/p/4861918.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值