日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

单链表的查找和取值-1

發布時間:2024/4/15 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 单链表的查找和取值-1 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題1:查找是否存在第i個元素,若存在用e返回第i個元素的值。不然返回0

查找部分算法:

(1)從第一個結點(L->next)順鏈掃描,用指針指向當前掃描到的節點,p初值p=L->next

(2)定義j作為計數器,累計當前掃描到的結點數,初值為1

(3)當p指向掃描到下一個節點時,計數器加1;

(4)開始循環,循環條件是p不為空和j<i;當j=i和p不為空時說明找到第i個元素

(5)當p為空或者j>i時說明第i元素不存在。

代碼:

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef struct LNode{
??????? int data;
??????? struct LNode *next;
}LNode,*LinkList;
//建立一個只含頭結點空鏈表
int InitList_L(LinkList &L){
??????? L=(LinkList)malloc(sizeof(LNode));
??????? if(!L){
??????????????? exit(OVERFLOW); // 存儲分配失敗
??????? }
??????? L->next=NULL;
??????? return OK;
}

//建立含n個元素的單鏈表,并且是尾插入,
int CreateList_L(LinkList &L,int n){
??????? LinkList p,q;
??????? int i;
??????? printf("Input the datas:");
??????? q=L;
??????? for(i=0;i<n;i++){
??????????????? p=(LinkList)malloc(sizeof(LNode));
??????????????? scanf("%d",&p->data);
??????????????? p->next=q->next;
??????????????? q->next=p;
??????????????? q=p;
??????? }
??????????????? return OK;
}

//若表中存在第i個元素,由變量e帶回其值
int GetElem_L(LinkList L,int i,int &e){
??????? LinkList p;
??????? int j=0;
??????? p=L;
??????? while(p&&j<i){??? //查找第i個元素
??????????????? p=p->next;
??????????????? ++j;
??????? }
??????? while(!p||j>i){
??????????????? return ERROR;
??????? }
??????? e=p->data;
??????? return OK;
}

//遍歷單鏈表L
int TraverseList_L(LinkList L){
??????? LinkList p;
??????? p=L->next;
??????? while(p){
??????????????? printf("%d",p->data);
??????????????? p=p->next;
??????? }
??????? return OK;
}
main(){
??????? int i,n,e;
??????? LinkList L;
??????? InitList_L(L);
??????? printf("Input the length of the list L:");
??????? scanf("%d",&n);
??????? CreateList_L(L,n);
??????? printf("Input the search location:");
??????? scanf("%d",&i);
??????? if(GetElem_L(L,i,e)){
??????????????? printf("The data in the location %d is %d\n",i,e);
??????? }else{
??????????????? printf("Can't find the right location!\n");
??????? }
??????? printf("Output the datas:");
??????? TraverseList_L(L);
??????? printf("\n");
}

結果:
android@android-Latitude-E4300:~/work/c/danlianbiao$ ./getelemlist
Input the length of the list L:5
Input the datas:1 3 5 7 9
Input the search location:3
The data in the location 3 is 5
Output the datas:13579




?

轉載于:https://www.cnblogs.com/shamoguzhou/p/6903116.html

總結

以上是生活随笔為你收集整理的单链表的查找和取值-1的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。