【问题描述】
已知非空线性链表第1个链结点指针为list,链结点构造为
struct node{
datatype data;
node *link;
};
请写一算法,将该链表中数据域值最大的那个点移到链表的最后面。(假设链表中数据域值最大的链结点惟一)(注意:要求先写出算法的解题思路,然后再写出算法)
【输入形式】
输入为一个整数序列,整数之间以空格隔开,序列以回车结尾。
【输出形式】
输出为移动后的整数序列,整数之间以空格隔开,序列以回车结尾。
【样例输入】
3 12 4 9 5 1
【样例输出】
3 4 9 5 1 12
【样例说明】
将序列中最大的数字12移动到序列最后。
我的思路:
1.先遍历链表找出那个最大值
2.尾插最大值
3.删最大值对应结点
代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int datatype;
typedef struct node {
datatype data;
struct node* link;
}node;
node* BuySLTNode(datatype x)
{
node* newnode = (node*)malloc(sizeof(node));
if (newnode == NULL)
{
perror("malloc fail");
exit(-1);
}
newnode->data = x;
newnode->link = NULL;
return newnode;
}
node* CreateSList()
{
datatype data;
node* phead = NULL, *ptail = NULL;
while(1)
{
scanf("%d", &data);
if (getchar() == '\n')
{
break;
}
node* newnode = BuySLTNode(data);
if (phead == NULL)
{
ptail = phead = newnode;
}
else
{
ptail->link = newnode;
ptail = newnode;
}
}
return phead;
}
node* Find_max(node* phead)
{
node* cur = phead;
node* Max = phead;
datatype max = cur->data;
while (cur)
{
if (cur->data > max)
{
max = cur->data;
Max = cur;
}
cur = cur->link;
}
return Max;
}
void SListErase(node** pphead, node* pos)
{
assert(pos);
assert(*pphead);
if (pos == *pphead)
{
node* next = (*pphead)->link;
free(*pphead);
*pphead = next;
}
else
{
node* prev = *pphead;
while (prev->link != pos)
{
prev = prev->link;
}
prev->link = pos->link;
free(pos);
}
}
void SLTPushBack(node** pphead, datatype x)
{
node* newnode = BuySLTNode(x);
if (*pphead == NULL)
{
*pphead = newnode;
}
else
{
node* tail = *pphead;
//找尾
while (tail->link)
{
tail = tail->link;
}
tail->link = newnode;
}
}
void SLTPrint(node* phead)
{
node* cur = phead;
while (cur)
{
printf("%d", cur->data);
cur = cur->link;
}
}
int main()
{
node* plist = (node*)malloc(sizeof(node));
plist = CreateSList();
node* max = Find_max(plist);
SLTPushBack(plist, max->data);
SListErase(plist, max);
SLTPrint(plist);
return 0;
}
但是打印结果如下:
试图调试的时候发现:
不知道是哪里出错了 希望得到帮助 非常感谢