单链表的查找和取值-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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对 Java 集合的巧妙利用
- 下一篇: TTL_CMOS_RS232区别