赞
踩
(完整代码在文章 "最…下方")
创建链表并初始化值
修改链表中指定位置数据
遍历输出链表查看结果
(下方为头部代码)
- //定义结构体
- typedef struct Node{
- int data; //数据域
- struct Node *next; //指针域
- }Node;
-
- void create(Node *head); //创建
- void alter(Node *head); //修改
- void print(Node *head); //输出
-
- int main(){
-
- Node *head = (Node *)malloc(sizeof(Node));
-
- create(head); //创建链表
-
- alter(head); //修改链表指定位置的值
-
- print(head); //遍历链表
-
- }

1、创建链表
- void create(Node *head){
-
- if(!head){
- return;
- }
-
- Node *q = head;
-
- for(int i=0;i<5;i++){
- Node *p = (Node *)malloc(sizeof(Node));
- p->data = i+1;
-
- q->next = p;
- q = q->next;
- }
-
- q->next = NULL;
-
- }

2、修改数据
这里将for循环 与 while循环 两种方式均展示出来。
- void alter(Node *head){
-
- if(!head){
- return;
- }
-
- Node *q = head;
-
- // for循环修改值
- for(int i=0; q->next; i++, q=q->next ){
- if(i==3){
- printf("请输入修改后的值:");
- scanf("%d",&q->data);
- }
- }
-
- // while循环修改值
- int count = 0; //定义计数器,用来统计循环次数 即结点位置
- while(q->next){
- count++;
- if(count ==3){
- printf("请输入修改后的值:");
- scanf("%d",&q->data);
- }
- }
-
- }

3、遍历链表
- void print(Node *head){
-
- if(!head) {
- return;
- }
-
- Node *q = head->next;
-
- while(q){
- printf("%d ",q->data);
- q = q->next;
- }
-
- }
完整代码板
- #include<stdio.h>
- #include<stdlib.h>
-
- typedef struct Node{
- int data;
- struct Node *next;
- }Node;
-
- void create(Node *head);
- void alter(Node *head);
- void print(Node *head);
-
- int main(){
-
- Node *head = (Node *)malloc(sizeof(Node)) ;
-
- create(head);
-
- alter(head);
-
- print(head);
-
- }
-
- void create(Node *head){
-
- if(!head){
- return;
- }
-
- Node *q = head;
-
- for(int i=0;i<5;i++){
- Node *p = (Node *)malloc(sizeof(Node));
- p->data = i+1;
-
- q->next = p;
- q = q->next;
- }
-
- q->next = NULL;
-
- }
-
- void alter(Node *head){
-
- if(!head){
- return;
- }
-
- Node *q = head;
-
- for(int i=0; q->next; i++, q=q->next ){
- if(i==3){
- printf("请输入修改后的值:");
- scanf("%d",&q->data);
- }
- }
-
- }
-
- void print(Node *head){
-
- if(!head) {
- return;
- }
-
- Node *q = head->next;
-
- while(q){
- printf("%d ",q->data);
- q = q->next;
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。