删除链表中等于给定值val的所有节点

本文详细介绍如何实现删除链表中特定值的所有节点、删除已排序链表中的重复节点以及从尾到头打印链表的方法。提供了完整的C++代码实现,并通过示例展示了如何使用这些函数。

(1)删除链表中等于给定值val的所有节点
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
(2)删除链表中重复的结点
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
(3)从尾到头打印链表

//笔试题:
/*
删除链表中等于给定值val的所有节点。
样例:
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
*/
struct Node{
    int value;
    Node* next;
};

Node* CreatNode(int value, Node* next = NULL){
    Node* node = new Node;
    node->value = value;
    node->next = next;
    return node;
}
Node* Delete(Node* head, int x){
    if (head == NULL){
        return head;
    }

    Node* prev = head;
    Node* cur = head->next;

    while (cur != NULL){
        if (x == cur->value){
            prev->next = cur->next;
            cur = cur->next;
        }
        else{
            prev = cur;
            cur = cur->next;
        }
    }

    if (x == head->value){
        head = head->next;
        }
    return head;
}

//打印链表
void PrintList(Node* head){
    Node* curr = head;
    while (curr != NULL){
        cout << curr->value << ends;
        curr = curr->next;
    }
    cout << endl;
}

//面试题5:从尾到头打印链表
void PrintListFromTail(Node* head){
    if (head == NULL){
        return;
    }
    else{
        PrintListFromTail(head->next);
        cout << head->value << ends;
    }
}

测试

void test(){
    Node* g = CreatNode(5);
    Node* f = CreatNode(4,g);
    Node* e = CreatNode(4,f);
    Node* d = CreatNode(3,e);
    Node* c = CreatNode(3,d);
    Node* b = CreatNode(2,c);
    Node* a = CreatNode(1,b);

    PrintList(a);

    Node* head=Delete(a, 3);
    PrintList(head);
    cout << endl;
    PrintListFromTail(head);

}
//删除已排序链表中重复的结点,重复节点不保留。
Node* DeleteDuplication(Node* head){
    if (head == NULL){
        return head;
    }

    Node* first = new Node;  //新建一个头结点就简单很多了
    first->next = head;

    Node* last = first;
    Node* curr = head;
    while (curr != NULL & curr->next != NULL){
        if (curr->value == curr->next->value){
            int v = curr->value;
            while (v == curr->value){
                curr = curr->next;
            }
            last->next = curr;
        }
        else{
            last = curr;
            curr = curr->next;
        }
    }
    return first->next;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值