#include<malloc.h>
#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define ElemType int
typedef int Status;
typedef struct LNode
{
ElemType data;
struct LNode* next;
}LNode, * LinkList;
// 創建單鏈表
LNode* creat()
{
LNode* head, * p;
head = new LNode;
p = head;
int x, cycle = 1;
while (cycle)
{
cout << "Please input the data for single linker : ";
cin >> x;
if (x != 0)
{
LNode * s = new LNode;
s->data = x;
cout << "Input data : " << x << endl;
p->next = s;
p = s;
}
else
{
cycle = 0;
cout << "Input done! " << endl;
}
}
p->next = NULL;
//cout << "\nFirst data of single linker is " << head->data << endl;
return head;
}
//列印單鏈表
void printL(LNode* head)
{
LNode* p = head;
p = p->next;
while (p != NULL)
{
cout << "Single Linker data is " << p->data << endl;
p = p->next;
}
}
// 單鏈表測長
int length(LNode* head)
{
int n = 0;
LNode* p = head;
while (p->next != NULL)
{
p = p->next;
n++;
}
return n;
}
void del_nolmal(LNode* head)
{
LNode* head1 = head;
LNode* p = head1->next;
int i;
int len = length(head1);
int max = p->data;
int min = p->data;
for (i = 0; i < len; i++)
{
p = p->next;
if (p!= NULL)
{
if (p->data > max)
{
max = p->data;
}
}
}
p = head1;
for (i = 0; i < len; i++)
{
p = p->next;
if (p!= NULL)
{
if (p->data < min)
{
min = p->data;
}
}
}
p = head1;
for (i = 0; i <= len; i++)
{
LNode* q = p->next; //p4記錄p3前一個資料元素
if(q!=NULL)
{
if ((q->data<max) || p->data>min)
if (q->next != NULL)
{
p->next = q->next;
}
else
{
p->next = NULL;
}
}
}
free(p);
}
int main()
{
cout << "***創建單鏈表***" << endl;
LNode *head=creat();
cout << endl;
cout << "***列印單鏈表***" << endl;
printL(head);
cout << endl;
printf("len=%d",length(head));
del_nolmal(head);
cout << endl;
cout << "***列印單鏈表***" << endl;
printL(head);
cout << endl;
}
uj5u.com熱心網友回復:
s->data = x;cout << "Input data : " << x << endl;
p->next = s;
p = s;
這兒錯了
uj5u.com熱心網友回復:
那我這里應該怎么改呢
uj5u.com熱心網友回復:
應該s=p吧,不知道你的設計是不是這樣uj5u.com熱心網友回復:
create函式的分配記憶體處理改為if(x!=0)
{//此處開始代碼改變
if(p!=head) {
p->next = new LNode;
p=p->next;
}
p->data=https://bbs.csdn.net/topics/x;
}
else //此處開始代碼不變
不知道del_normal想干啥?是要洗掉max和min以外的元素嗎?在最后的for里,p一直沒變過,也就是p一直是head1,變的只是p->next,所以最后free(p)就會釋放整個鏈表(相當于free(head1),head1==head),所以main最后列印printL(head)就會出錯
uj5u.com熱心網友回復:
del_normal如果只想保留最大最小值,那就修改代碼for(i=0; i<len; i++)
{
if(p!=NULL&&p->next!=NULL)
{
if(p->next->data<max&&p->next->data>min)
{
LNode *q=p->next; //記錄p->next
p->next = q->next; //修改p->next為p->next->next
free(q);//把q節點洗掉
}
}
if(p!=NULL)
p=p->next;//移動節點
}
uj5u.com熱心網友回復:
感謝大佬,我仔細琢磨一下
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/59044.html
標籤:C++ 語言
