• Remove Linked List Elements


    Description:

    Remove all elements from a linked list of integers that have value val.

    Example
    Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
    Return: 1 --> 2 --> 3 --> 4 --> 5

    Code1:

     1   ListNode* removeElements(ListNode* head, int val) {
     2         if (head==NULL)
     3         {
     4             return NULL;
     5         }
     6         
     7         //在链表两端分别插入头结点和尾结点
     8         ListNode* headNode = new ListNode(0);
     9         headNode->next = head;
    10         
    11         ListNode* q = headNode;
    12         while (q->next)
    13         {
    14             q = q->next;
    15         }
    16         ListNode* tailNode = new ListNode(0);
    17         q->next = tailNode;
    18         
    19         q = head;
    20         ListNode* preNode = headNode;//指向被删结点的上一个结点
    21         while (q!=tailNode)
    22         {
    23             if (q->val == val)
    24             {
    25                 preNode->next = q->next;
    26                 delete q;
    27                 q = preNode->next;
    28             }
    29             else
    30             {
    31                 q=q->next;
    32                 preNode=preNode->next;
    33             }
    34         }
    35         
    36         if (headNode == tailNode)
    37             return NULL;
    38         else
    39         {
    40             preNode->next = NULL;
    41             head = headNode->next;
    42             delete headNode;
    43             delete tailNode;
    44             return head;
    45         }
    46     }
    View Code

    Code2:

     1   ListNode* removeElements(ListNode* head, int val) {
     2         if (head==NULL)
     3         {
     4             return NULL;
     5         }
     6 
     7         ListNode* q = head;
     8         ListNode* preNode = NULL;//指向被删结点的上一个结点
     9         while (q!=NULL)
    10         {
    11             if (q->val == val)
    12             {
    13                 if (q == head)
    14                 {
    15                     head = head->next;
    16                     delete q;
    17                     q = head;
    18                 }
    19                 else
    20                 {
    21                     preNode->next = q->next;
    22                     delete q;
    23                     q = preNode->next;
    24                 }
    25             }
    26             else
    27             {
    28                 preNode = q;
    29                 q=q->next;
    30             }
    31         }
    32      return head;
    33     }
    View Code
  • 相关阅读:
    实验5 函数
    实验4 在分支循环结构中调用自定义函数
    Play 内置标签
    POI 正常输出WORD 文档
    用户WORD模板写文件
    Spring 注解过滤
    Spring 循环依赖
    Spring 表单标签
    WebService 客户端生成服务端代码
    Jquery 常用函数
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4599661.html
Copyright © 2020-2023  润新知