6、移除链表元素

方法1:原链表删除元素

 伪代码:

        首先判断头节点是否是待删除元素。(头节点和其他节点的删除方法不一样)

while(head != null && head->value == target)
//如果链表为 1 1 1 1 1,要删除元素1时用if就会失效
{
    head = head->next;
}
cur = head;
//为什么不是从head->next开始
//因为不方便删除链表节点,如果指向head->next的话,head会丢失,不方便删除链表节点
while(cur != null && cur ->next != null)
{
    if(cur->next->value == target)
    {
        cur->next = cur->next->next;
    }
    else
    {
        cur = cur->next;
    }
}
return head;

方法2:虚拟头节点

        增加一个虚拟头节点,如果删除的是头节点,那么直接删除就行。

伪代码:

dumyhead = new();//创建虚拟头节点
dumyhead->next = head;
cur = dumy->head;
while(cur->next != null)
{
    if(cur->next->value = target)
        cur->next = cur->next->next;
    else
        cur = cur->next;
}
return dumyhead->next;

你可能感兴趣的:(c语言,c++算法刷题笔记,链表,数据结构)