求最小(大)值
首先标记一个元素,然后扫描整个线性表,如果发现更小(大)的元素就更新标记
/*线性表求最大值*/
int max = a[0];
int maxIdx = 0;
for(int i=0; i<n; ++i)
{
if(max < a[i])
{
max = a[i];
maxIdx = i;
}
} //顺便求了位置
/*线性表求最小值*/
int min = a[0];
int minIdx = 0;
for(int i=0; i<n; ++i)
{
if(min > a[i])
{
min = a[i];
minIdx = i;
}
}
/*链表的标记换成指针*/
LNode *p, *q;
int min = head->next->data;
q = p = head->next;
while(p != NULL)
{
if(min > p->data)
{
min = p->data;
q = p;
}
p = p->next;
}
真题举例
一双链表非空,由head指针指出,节点结构为{llink, data, rlink},请设计一个将节点数据域data值最大的那个节点(最大值节点只有一个)移动到链表最前边的算法,要求不得申请新节点空间
我的解答
/*为了检查两个方向的指针是否都正确,加了一个tail便于反向打印*/
#include <iostream>
using namespace std;
struct LNode
{
int data = 0;
struct LNode* llink = nullptr, *rlink = nullptr;
};
void CreateTable(LNode*& head, LNode*& tail)
{
head = new LNode;
int n;
cin >> n;
tail = head;
for (int i = 0; i < n; i++)
{
int d;
cin >> d;
tail->rlink = new LNode;
tail->rlink->data = d;
tail->rlink->llink = tail;
tail = tail->rlink;
}
}
void PrintTableR(LNode* head)
{
LNode* p = head->rlink;
while (p != nullptr)
{
cout << p->data << " ";
p = p->rlink;
}
cout << endl;
}
void PrintTableL(LNode* tail, LNode* head)
{
LNode* p = tail;
while (p!=head)
{
cout << p->data << " ";
p = p->llink;
}
cout << endl;
}
void MoveMaxToHead(LNode*& head, LNode*& tail)
{
LNode* p, * q;
int max = head->rlink->data;
q = p = head->rlink;
while (p != nullptr)
{
if (max < p->data)
{
max = p->data;
q = p;
}
p = p->rlink;
}
if (q != tail)
q->rlink->llink = q->llink;
else
tail = q->llink;
q->llink->rlink = q->rlink;
q->rlink = head->rlink;
q->llink = head;
q->rlink->llink = q;
head->rlink = q;
}
int main()
{
LNode* head, * tail;
CreateTable(head, tail);
PrintTableL(tail, head);
PrintTableR(head);
MoveMaxToHead(head, tail);
cout << "-------------------------------------------" << endl;
PrintTableR(head);
PrintTableL(tail, head);
system("pause");
}
标准答案
void maxFirst(DLNode* head) //head不改变,不用引用
{
DLNode* p = head->rlink, *q = p;
int max = p->data;
//找最值
while(p != NULL)
{
if(max < p->data)
{
max = p->data;
q = p;
}
p = p->rlink;
}
//伪"删除":不需要delete
DLNode* l = q->llink, *r = q->rlink;
l->rlink = r;
if(r != NULL)
r->llink = l;
//插入
q->llink = head;
q->rlink = head->rlink;
head->rlink = q;
q->rlink->llink = q;
}