注意:现在偷的懒以后都要补回来的!
希望大家认真学好数据结构,不希望后悔!
- 【函数】在顺序表中,输入一个元素插入到原表的最大元素之前
【问题描述】
设有顺序表,输入一个元素插入到顺序表最大元素之前。
【输入形式】
第一行输入一个N(N>=0且N<=100);
第二行输入N个整数(以空格分隔);
第三行输入一个整数(将该整数插入到顺序表最大元素之前)
【输出形式】
输出插入后的顺序表元素
【样例输入】
5
12 98 34 -87 -23
20
【样例输出】
12 20 98 34 -87 -23
#include <stdio.h>
#include <stdlib.h>
typedef struct List{
int length;
int *item;
}List;
int main()
{
int n,m,pos;
int count,index;
scanf("%d",&n);
List list;
list.item=(int *)malloc(sizeof(int)*(n+1));
list.length=0;
for(int i=0;i<n;i++){
scanf("%d",&m);
if(i==0){
count=m;
index=i;
}else{
if(count<m){
count=m;
index=i;
}
}
list.item[i]=m;
list.length++;
}
scanf("%d",&pos);
int i;
for(i=n-1;i>=index;i--){
list.item[i+1]=list.item[i];
}
list.item[index]=pos;
list.length++;
for(int j=0;j<list.length;j++){
printf("%d ",list.item[j]);
}
return 0;
}
- 【函数】在带头结点单链表中查找最大值,将其与最后一个元素交换
【问题描述】
在带头结点单链表中查找最大值,将其值与最后一个元素交换,输出交换后的单链表各元素。
【输入形式】
循环输入若干个整数,以字母结束输入,建立带头结点的单链表。
【输出形式】
输出最大值与最后一个元素交换后的单链表元素。
【样例输入1】
10 8 2 55 6 7 40 a
【样例输出1】
10 8 2 40 6 7 55
【样例输入2】
-5 -12 -8 -1 -10 -3 e
【样例输出2】
-5 -12 -8 -3 -10 -1
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node;
int main()
{
int n,m,sum,sum2;
int count=1;
Node *node,*head,*z,*x,*q,*p;
head=(Node *)malloc(sizeof(Node));
head->next=NULL;
z=head;
while(scanf("%d",&n)==1){
node=(Node *)malloc(sizeof(Node));
node->next=NULL;
node->data=n;
if(count==1){
sum=n;
count++;
}else{
if(sum<n){
sum=n;
}
}
sum2=n;
z->next=node;
z=node;
}
getchar();
p=head->next;
while(p){
if(p->data==sum){
p->data=sum2;
}else{
if(p->data==sum2){
p->data=sum;
}
}
printf("%d ",p->data);
p=p->next;
}
return 0;
}
- 【函数】在带头结点的单链表中查找倒数第k个结点数据
【问题描述】
在带头结点的单链表中查找倒数第k个结点,如果查找成功,根据传地址参数保存结点的值。
【输入形式】
第一行输入n个整数建立单链表(以非整数结束输入),第二行输入k,表示需要查找倒数第k个结点。
【输出形式】
输出倒数第k个结点的数据值,如果没有找到则输出*。
【样例输入1】
10 20 33 45 58 a
2
【样例输出1】
45
【样例输入2】
10 20 33 45 58 a
7
【样例输出2】
*
【样例输入3】
a
7
【样例输出3】
*
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node;
int main()
{
int n,m,sum,flag=0;
int count=0;
Node *node,*head,*z,*p;
head=(Node *)malloc(sizeof(Node));
head->next=NULL;
z=head;
while(scanf("%d",&n)==1){
node=(Node *)malloc(sizeof(Node));
node->next=NULL;
node->data=n;
z->next=node;
z=node;
count++;
}
getchar();
p=head->next;
scanf("%d",&m);
if(m>count){
printf("*");
}else{
while(p){
flag++;
if(count-m+1==flag){
printf("%d",p->data);
}
p=p->next;
}
}
return 0;
}