最开始的错误代码以及做题思路和草稿纸上写的过程画的图:
#include<stdio.h>
#include<stdlib.h> //提供malloc()和free()
#include<string.h> //提供strcpy()等
struct Node
{
int data; //数据域
struct Node* next; //指针域(指向节点的指针)
};
struct Node* head;
struct Node* newNode;
int n;
void CreateLinkList()//创建新链表
{
scanf("%d",&n);//输入单链表的长度
struct Node *q,*tail;
for(int i=0; i<n; i++)
{
q=(struct Node*)malloc(sizeof(struct Node));
q->next=NULL;
scanf("%d",&(q->data));
//分类讨论,头节点和其他节点
if(i==0){
head=q;
tail=q;
}else{
tail->next=q;
tail=q;
}
}
}
void PrintLinkList()//打印修改后的链表
{
struct Node *p;
p=head;
while(p)
{
printf("%d ",p->data);
p=p->next;//指针移动到下个元素的首地址
}
printf("\n");
}
struct Node *minNode,*pcurrent;
void FindminNode()//找到最小的结点并删除
{
minNode=head;
pcurrent=head;
int i=0,k=1;
while(pcurrent)
{
i++;
if(pcurrent->data<minNode->data)
{
minNode=pcurrent;
k=i;
}
pcurrent=pcurrent->next;
}
pcurrent=head;
for(int i=0;i<k;i++)
{
if(i == k-1)//删除最小的结点
{
minNode = pcurrent->next;
pcurrent = minNode->next;
}
pcurrent=pcurrent->next;
}
}
void InsertForward()//头插法
{
minNode->next=NULL;
minNode->next=head->next;
head->next=minNode;
}
int main()
{
CreateLinkList();
FindminNode();
InsertForward();
PrintLinkList();
return 0;
}
没有输出结果,确定输入输出函数没有问题,问题出在FindminNode()函数里,但是不好改哪了,就问了学姐,帮我改了两个地方
改动前: 改动后:
其实开始有分开讨论k=1和k>1的情况,但后面觉得删除节点再插入到开头是一样的,就没有分开讨论了。
改动后的代码,过了,整体思路没问题,就是要注意头尾节点的特殊情况和指针指向的位置:
#include<stdio.h>
#include<stdlib.h> //提供malloc()和free()
#include<string.h> //提供strcpy()等
struct Node
{
int data; //数据域
struct Node* next; //指针域(指向节点的指针)
};
struct Node* head;
struct Node* newNode;
int n;
void CreateLinkList()//创建新链表
{
scanf("%d",&n);//输入单链表的长度
struct Node *q,*tail;
for(int i=0; i<n; i++)
{
q=(struct Node*)malloc(sizeof(struct Node));
q->next=NULL;
scanf("%d",&(q->data));
//分类讨论,头节点和其他节点
if(i==0)
{
head=q;
tail=q;
}
else
{
tail->next=q;
tail=q;
}
}
}
void PrintLinkList()//打印修改后的链表
{
struct Node *p;
p=head;
while(p)
{
printf("%d ",p->data);
p=p->next;//指针移动到下个元素的首地址
}
printf("\n");
}
struct Node *minNode,*pcurrent;
void FindminNode()//找到最小的结点并删除
{
minNode=head;
pcurrent=head;
int i=0,k=1;
while(pcurrent)
{
i++;
if(pcurrent->data<minNode->data)
{
minNode=pcurrent;
k=i;
}
pcurrent=pcurrent->next;
}
pcurrent=head;
for(int i=0; i<k; i++)
{
if(k==1){
head=head->next;
minNode->next=NULL;
break;
}
if(i == k-2)//删除最小的结点
{
/*minNode = pcurrent->next;
pcurrent = minNode->next;*/
pcurrent->next= pcurrent->next->next;
minNode->next=NULL;
break;
}
pcurrent=pcurrent->next;
}
//printf("===");
}
void InsertForward()//头插法
{
/*minNode->next=NULL;
minNode->next=head->next;
head->next=minNode;*/
minNode->next=head;
head=minNode;
}
int main()
{
CreateLinkList();
FindminNode();
InsertForward();
PrintLinkList();
return 0;
}