zoukankan      html  css  js  c++  java
  • 正整数构成的线性表存放在单链表中,编写算法将表中的所有的奇数删除。(C语言)

     1 /* 正整数构成的线性表存放在单链表中,编写算法将表中的所有的奇数删除 */
     2 #include <stdio.h>
     3 #include <stdlib.h>
     4 typedef struct LNode{
     5     int data;
     6     struct LNode *next;
     7 }LNode;
     8 LNode* creat(int n){
     9     LNode *Link;  
    10     LNode *p1,*p2;
    11     int data;
    12     Link=(LNode*)malloc(sizeof(LNode));
    13     p2=Link;
    14     for(int i=0;i<n;++i){  //一共n个数
    15         scanf("%d",&data);
    16         p1=(LNode*)malloc(sizeof(LNode));
    17         p1->data=data;
    18         p2->next=p1;
    19         p2=p1;
    20     }
    21     p2->next=NULL;
    22     return Link;
    23 }
    24 
    25 LNode *del(LNode *&A){
    26     LNode *p=A;  //p相当于A的头结点,后面接着链表A
    27     while(p->next!=NULL){   //从A链表的第一个结点(也就是p的下一个结点)开始遍历
    28         if(p->next->data%2!=0){
    29             LNode *t=p->next;   //t指针指向当前遍历到的奇数结点
    30             p->next=t->next;    //删除(p后面的)t结点(奇数结点)
    31             free(t);
    32         }
    33         else
    34             p=p->next;    //如果遍历到的当前结点非奇数结点,就将p指针后移
    35     }
    36     return A;
    37 
    38 }
    39 
    40 void print(LNode *Link){
    41     LNode *p;
    42     p=Link->next;
    43     while(p!=NULL){    
    44         printf("%d",p->data);
    45         printf(" ");
    46         p=p->next;
    47     }
    48     printf("
    ");
    49 }
    50 
    51 int main(){
    52     LNode *Link=NULL;
    53     int num;
    54     printf("共创建几个链表结点:");
    55     scanf("%d",&num);
    56     printf("请输入链表结点:
    ");
    57     Link=creat(num);
    58     printf("已创建好的链表结点:");
    59     print(Link);
    60     del(Link);
    61     print(Link);
    62     return 0;
    63 }

    运行结果如下:

  • 相关阅读:
    Leetcode Binary Tree Level Order Traversal
    Leetcode Symmetric Tree
    Leetcode Same Tree
    Leetcode Unique Paths
    Leetcode Populating Next Right Pointers in Each Node
    Leetcode Maximum Depth of Binary Tree
    Leetcode Minimum Path Sum
    Leetcode Merge Two Sorted Lists
    Leetcode Climbing Stairs
    Leetcode Triangle
  • 原文地址:https://www.cnblogs.com/tendo/p/9948291.html
Copyright © 2011-2022 走看看