mycwt60 发表于 2022-1-1 12:39:38

求助大佬C语言单链表按位置修改操作

单链表按位置修改操作,已知一个带头结点的单链表中包含5个结点,每个结点包含两个域,一个域为数据域(整型数据),另一个域为指针域,5个结点的数据域分别为22,7,45,89,78,从键盘输入两个整数,第一个整数为要修改的数据的位置,第二整数为修改后的数。输出前5个数(每个输出的数之间用一个空格隔开,最前面没有空格,最后有一个空格)。
输入示例:2 88
输出示例:22 88 45 89 78
#include<stdio.h>
#include<malloc.h>
typedef struct LNode{
int data;
struct LNode* next;
}LNode,*LinkList;
int main(){
int arr[]= {22,7,45,89,78};
int n = 5,pos,x,j;
LinkList rear,p,q;
//尾插法创建链表 P是链表长度
LinkList head =
(LinkList)malloc(sizeof(LNode));
head->next = NULL;
rear = head;
for(int i=0;i<n;i++){
p = (LinkList)malloc(sizeof(LNode));
p->data = arr;
p->next = NULL;
rear->next = p;
rear = p;
}

傻眼貓咪 发表于 2022-1-1 13:04:35

#include <stdio.h>
#include <stdlib.h>

struct Node{
    int data;
    struct Node* next;
};

int main(){
    int arr[] = {22, 7, 45, 89, 78};
    struct Node *head = NULL, *tail = NULL;
   
    for(int i = sizeof(arr)/sizeof(int)-1; i > -1; i--){
      tail = head;
      head = (struct Node*)malloc(sizeof(struct Node));
      head->data = arr;
      head->next = tail;
    }
   
    int a, b;
    scanf("%d%d", &a, &b);
   
    struct Node *p = head;
    for(int i = 0; p; i++, p = p->next) if(i+1 == a) p->data = b;
   
    while(head){
      printf("%d ", head->data);
      head = head->next;
    }
    return 0;
}

mycwt60 发表于 2022-1-1 17:14:03

傻眼貓咪 发表于 2022-1-1 13:04


大佬, 求您解答一下单链表按位置插入操作{:5_100:}
22,7,45,89,78
输入示例:2 88
输出示例:22 88 7 45 89"

傻眼貓咪 发表于 2022-1-1 17:17:13

mycwt60 发表于 2022-1-1 17:14
大佬, 求您解答一下单链表按位置插入操作
22,7,45,89,78
输入示例:2 88


题目要求:单链表按位置插入操作

单链表的初始数据:22 7 45 89 78
输入示例:2 88
输出示例:22 88 7 45 89

这里可以看出第 2 位置就是数字 7
把 7 换成 88 就是解答

mycwt60 发表于 2022-1-1 17:52:02

傻眼貓咪 发表于 2022-1-1 17:17
题目要求:单链表按位置插入操作

单链表的初始数据:22 7 45 89 78


把第二位的7换成88,之前的第二位和后面的位 都要向后挪动一个位置 这个语法上该怎么写 int temp;
for(int i = 0; p; i++, p = p->next)
temp=p->data;
p->data = b;
p->next=temp;

傻眼貓咪 发表于 2022-1-1 18:52:29

mycwt60 发表于 2022-1-1 17:52
把第二位的7换成88,之前的第二位和后面的位 都要向后挪动一个位置 这个语法上该怎么写

哦哦,我还以为你问同一题,你要的插入法:#include <stdio.h>
#include <stdlib.h>

struct Node{
    int data;
    struct Node* next;
};

int main(){
    int arr[] = {22, 7, 45, 89, 78}, N = 5;
    struct Node *head = NULL, *tail = NULL;
   
    for(int i = N-1; i > -1; i--){
      tail = head;
      head = (struct Node*)malloc(sizeof(struct Node));
      head->data = arr;
      head->next = tail;
    }
   
    int a, b;
    scanf("%d%d", &a, &b);
   
    struct Node *p = head;
    struct Node *t = NULL;
    for(int i = 0; i < N-1; i++, p = p->next)
    if(i+1 == a){
      t = (struct Node*)malloc(sizeof(struct Node));
      t->data = p->data;
      t->next = p->next;
      p->data = b;
      p->next = t;
    }
    p->next = NULL;
    while(head){
      printf("%d ", head->data);
      head = head->next;
    }
    return 0;
}输出结果:2 88
22 88 7 45 89

mycwt60 发表于 2022-1-1 19:31:22

傻眼貓咪 发表于 2022-1-1 18:52
哦哦,我还以为你问同一题,你要的插入法:输出结果:

谢谢大佬
页: [1]
查看完整版本: 求助大佬C语言单链表按位置修改操作