数据结构上机测试2-2:单链表操作B
題目描述
按照數(shù)據(jù)輸入的相反順序(逆位序)建立一個單鏈表,并將單鏈表中重復的元素刪除(值相同的元素只保留最后輸入的一個)。輸入
第一行輸入元素個數(shù)n;第二行輸入n個整數(shù)。
輸出
第一行輸出初始鏈表元素個數(shù);第二行輸出按照逆位序所建立的初始鏈表;
第三行輸出刪除重復元素后的單鏈表元素個數(shù);
第四行輸出刪除重復元素后的單鏈表。
示例輸入
10 21 30 14 55 32 63 11 30 55 30示例輸出
10 30 55 30 11 63 32 55 14 30 21 730 55 11 63 32 14 21
#include <iostream> #include<bits/stdc++.h> using namespace std; struct node {int data;node *next; }; struct node *create(int n) {int i;node *head,*p;head=new node;head->next=NULL;for(i=0;i<n;i++){p=new node;scanf("%d",&p->data);p->next=head->next;head->next=p;}return (head); }; void print(struct node *p) {struct node *h=p->next;while(h!=NULL){if(h->next==NULL)printf("%d",h->data);elseprintf("%d ",h->data);h=h->next;} } void num(node *head) {int i=0;node *p=head->next;while(p){i++;p=p->next;}printf("%d\n",i); } void del(node *p)//刪除重復元素; {node *h;h=p->next;node *q,*t;while(h){q=h;while(q->next){if(h->data==q->next->data){t=q->next;q->next=t->next;free(t);}elseq=q->next;}h=h->next;} } int main() {int n;scanf("%d",&n);node *p=create(n);num(p);print(p);printf("\n");del(p);num(p);print(p);return 0; }
總結
以上是生活随笔為你收集整理的数据结构上机测试2-2:单链表操作B的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 赫夫曼编码长度计算问题?
- 下一篇: inline函数和一般的函数有什么不同