zoukankan      html  css  js  c++  java
  • CCI_Q2.1

    本文参考该作者文章当作编程笔记:
    
    作者:Hawstein
    出处:http://hawstein.com/posts/ctci-solutions-contents.html

    一.

    Q:

    从一个未排序的链表中移除重复的项

    进一步地,

    如果不允许使用临时的缓存,你如何解决这个问题?

    思路:

    removedulicate():额外开一Boolen数组dulicate[N]存放链表中的数据,遍历链表,将链表的item对应的数组中的元素设为真。如果某元素在数组中为真,证明它前面出现过,删除即可。缺点:链表的item类型为int型时,1,可能为负值;2,浪费空间。

    removeDulicate():双层循环遍历链表,重复即删除。

    Talk is cheap,Show me CODE:

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<memory.h>
     4 #define N 10
     5 typedef struct node *link;
     6 struct node
     7 {
     8     int item;
     9     link next;
    10 }head;
    11 int dulicate[N];
    12 void init(int s[])
    13 {
    14     int i;
    15     link p=&head;
    16     for(i=0;i<N;i++)
    17     {
    18         p->next=malloc(sizeof(*p));
    19         p=p->next;p->next=NULL;
    20         p->item=s[i];
    21     }
    22 }
    23 void removedulicate()
    24 {
    25     link p=&head;
    26     while(p->next!=NULL)
    27     {
    28         int    c=p->next->item;
    29         if(dulicate[c]==1)
    30         {
    31             link t=p->next;
    32             p->next=t->next;
    33             free(t);
    34         }
    35         else
    36         {
    37             dulicate[c]=1;
    38             p=p->next;
    39         }
    40     }
    41 }
    42 void removeDulicate()
    43 {
    44     link p=&head;
    45     while(p->next!=NULL)
    46     {
    47         int c=p->next->item;
    48         link q=p->next;
    49         while(q->next!=NULL)
    50         {
    51             if(c==q->next->item)
    52             {
    53                 link t=q->next;
    54                 q->next=t->next;
    55                 free(t);
    56             }
    57             else
    58                 q=q->next;
    59         }
    60         p=p->next;
    61     }
    62 }
    63 void printList()
    64 {
    65     link p=&head;
    66     while(p->next!=NULL)
    67     {
    68         p=p->next;
    69         printf("%d	",p->item);
    70     }
    71     printf("
    ");
    72 }
    73 int main()
    74 {
    75     int s[N]={1,3,4,5,4,3,7,2,1,3};
    76     memset(dulicate,0,sizeof(dulicate));
    77     head.next=NULL;
    78     init(s);
    79     printList();
    80 //    removedulicate();
    81     removeDulicate();
    82     printList();
    83     return 0;
    84 }
  • 相关阅读:
    bzoj3796
    bzoj2186
    bzoj3769
    bzoj2660
    bzoj2245
    bzoj2916
    bzoj1261
    在IDEA中以TDD的方式对String类和Arrays类进行学习
    2018-2019-2 实验二《Java面向对象程序设计》实验报告
    《Java程序设计》第 6 周学习总结
  • 原文地址:https://www.cnblogs.com/jhooon/p/3579899.html
Copyright © 2011-2022 走看看