2020-08-20[打印单链表中间位置元素的值]

2020-08-20  本文已影响0人  金珉锡_4bc1
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

/**
    打印单链表中间位置元素的值
    */ 

typedef struct Node
{
    int data;
    struct Node* Next;
} Node;
typedef struct Node* LinkList;

// 创建一个长度为n的链表 
void createLinkList(LinkList *L, int n)
{
    srand(time(0)); 
    
    *L = (LinkList)malloc(sizeof(Node));
    LinkList p = *L;
    
    for(int i = 0; i < n; i++){
        LinkList q = (LinkList)malloc(sizeof(Node));
        q->data = rand() % 100 + 1;
        p->Next = q;
        p = q;
    }
    
    p->Next = NULL;
}

// 获取链表中间的元素 
void GetMidNode(LinkList L, int *D)
{
    LinkList search, mid;
    search = mid = L;
    
    while(search->Next != NULL){
        if(search->Next->Next != NULL){
            search = search->Next->Next;
            mid = mid->Next;            
        }
        else{
            search = search->Next;
        }
    }   
    
    *D = mid->data;
}

void PrintLinkList(LinkList L)
{
    LinkList p = L->Next;
    while(p->Next != NULL){
        printf("%d ", p->data);
        p = p->Next;
    }
    printf("\n");
}

int main(int argc, char *argv[])
{
    LinkList l;
    int Data;
    
    createLinkList(&l, 20);     
    
    PrintLinkList(l);   
    
    GetMidNode(l, &Data);
    
    printf("链表中间的元素值为:%d\n", Data);
    
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读