链表笔记(自用)

 链表定义(来源leetcode)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

获取链表长度

int getLength(ListNode* head){
        int count=0;
        while(head){
            count++;
            head=head->next; 
        }
        return count;
    }

删除链表重复元素

ListNode* deleteDuplicates(ListNode* head) {   
        ListNode *cur=head;
        while(cur&&cur->next){
            if(cur->val==cur->next->val){
                //ListNode *del=cur->next;
                cur->next=cur->next->next;
                //delete del;
            }else
                cur=cur->next;
        }
        return head;
    }

删除链表倒数第n个元素

ListNode* removeNthFromEnd(ListNode* head, int n) {
        //虚拟节点,避免头节点为空的现象;
        ListNode* dummy=new ListNode(0,head);     //the first member val to 0, and the second member next to head
        int length=getLength(head);
        ListNode* curr=dummy;
        for(int i=1;i<length-n+1;i++){      //最终将curr定位在待删除元素前一个位置
            curr=curr->next;
        }
        curr->next=curr->next->next;
        ListNode *ans=dummy->next;
        delete dummy;
        return ans;
    }

返回链表的中间节点,如果有两个,返回后一个

ListNode* middleNode(ListNode* head) {
        //快慢指针
        ListNode* fast=head;
        ListNode* slow=head;
        while(fast && fast->next){
            slow=slow->next;
            fast=fast->next->next;
        }
        return slow;
    }

反转链表

 ListNode* reverseLinkList(ListNode* head){
        ListNode* curr=head;
        ListNode* pre=nullptr;
        while(curr){
            ListNode* nextTemp=curr->next;
            curr->next=pre;
            pre=curr;
            curr=nextTemp;
        }
        return pre;
    }

寻找链表中间节点(数组法)

ListNode* middleNode(ListNode* head) {
        //数组
        vector<ListNode*> LinkList={head};
        while(LinkList.back()->next)
            LinkList.push_back(LinkList.back()->next);
        return LinkList[LinkList.size()/2];

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值