低端一点,不要太高级
编程题,急求 已知非空线性链表head,编写程序,将链表中数据域值最小的那个结点移至表的最前面。要求:不得额外申请新的结点。
答案:2 悬赏:20 手机版
解决时间 2021-05-10 18:32
- 提问者网友:放下
- 2021-05-10 10:54
最佳答案
- 五星知识达人网友:怀裏藏嬌
- 2021-05-10 11:13
这是我在以前写的代码的基础上修改的,main里完成的就是找出最小值节点然后插入表头:
#include <stdio.h>
#include <stdlib.h>
typedef struct _list {
int val;
struct _list* next;
} *node, list;
node Insert( node* head, node pos, int val )
{
node tmp;
tmp = ( node )malloc( sizeof( list ) );
tmp->val = val;
tmp->next = pos ? pos->next : *head;
if ( pos ) {
pos->next = tmp;
} else {
*head = tmp;
}
return tmp;
}
node Create( int* beg, int* end )
{
node head, t;
head = t = NULL;
while ( beg != end ) {
t = Insert( &head, t, *beg++ );
}
return head;
}
void Print( node head )
{
while ( head ) {
printf( "%d ", head->val );
head = head->next;
}
putchar( '\n' );
}
int main()
{
int a[] = { 6,1,3,9,2,8,5,0,7,4 };
node head, min, prev, next;
head = Create( a, a + 10 );
Print( head );
min = prev = next = head;
while ( next->next ) {
if ( min->val > next->next->val ) {
prev = next;
min = next->next;
}
next = next->next;
}
prev->next = min->next;
min->next = head;
head = min;
Print( head );
getchar();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct _list {
int val;
struct _list* next;
} *node, list;
node Insert( node* head, node pos, int val )
{
node tmp;
tmp = ( node )malloc( sizeof( list ) );
tmp->val = val;
tmp->next = pos ? pos->next : *head;
if ( pos ) {
pos->next = tmp;
} else {
*head = tmp;
}
return tmp;
}
node Create( int* beg, int* end )
{
node head, t;
head = t = NULL;
while ( beg != end ) {
t = Insert( &head, t, *beg++ );
}
return head;
}
void Print( node head )
{
while ( head ) {
printf( "%d ", head->val );
head = head->next;
}
putchar( '\n' );
}
int main()
{
int a[] = { 6,1,3,9,2,8,5,0,7,4 };
node head, min, prev, next;
head = Create( a, a + 10 );
Print( head );
min = prev = next = head;
while ( next->next ) {
if ( min->val > next->next->val ) {
prev = next;
min = next->next;
}
next = next->next;
}
prev->next = min->next;
min->next = head;
head = min;
Print( head );
getchar();
return 0;
}
全部回答
- 1楼网友:梦中风几里
- 2021-05-10 11:29
新建一个指针和数据变量,将第一个结点的数据赋给数据变量,然后再用它与其他结点进行比较,一旦找到比它小的就把那个结点的值赋给它,然后继续比较下去,最后得出最小结点数据的值,然后进行第二次比较,找出最小结点的所在,再把最小结点的直接前驱的next指向最小结点的直接后继,最后最小结点的next指向原来的第一个结点,并且把它的地址赋给head。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯