链表相关的试题连载

版权声明:作者:weizu_cool https://blog.csdn.net/qq_26460841/article/details/83217366

链表相关的试题连载

说明
这是在复习考研数据结构时候的试题的编写和整理。包含王道和天勤。主要是对编程题的练习,不涉及填空题等。

这里首先给出的是链表的定义相关的自定义头文件:

 - 数据结构格式:
lianbiao.h  在编写的cpp文件中,#include “lianbiao.h”中引入就可以了。
#ifndef CRYU_H //如果没有定义CRYU_H
#define CRYU_H //定义
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

typedef int ElemType;
//单链表 
typedef struct Node {
	ElemType num;
    struct Node * next;
}Node;

//有了链表中结点的数据结构,我们一起来建立单链表:
/*
    这里创建函数返回创建好的包含头结点的单链表:
     @int arr[] 是用于建立链表的数据
     @int size 是数组的长度
    这里传入长度是因为,形式参数中传入的是arr[] ,也就是一个数组的指针变量
    我们这里不能用sizeof(arr)/sizeof(arr[0])来获取
     @return Node*L 创建好的链表的指针
*/
Node* createList(ElemType arr[], int size, bool hasHead){
    int n = 0,num = 0;
	Node* first = (Node*)malloc(sizeof(Node));
    first->next = NULL;
    Node *p = first;
    int index ;
    if(!hasHead){
    	first->num = arr[0];
    	index = 1;
    	size--;
	}else{
		index = 0;
	}
	while(size>0){
		Node* node = (Node*)malloc(sizeof(Node));
		node->num = arr[index];
		index++;
		size--;

        // insert of tail 尾插
        node->next = p->next;
        p->next = node;
        p=node;
        
        // insert of head 头插
		// node->next = first->next;
		// first->next = node;
	}
    return first;
}
//上面的函数中,有两种模式的数据插入方法,分别头插法和尾插法,这里我默认是尾插,你不妨打开头插注释,注释尾插,实验实验头插。
//有了创建链表,我们希望看见输出:
/*
    @Node* L 这是单链表的头结点的指针
*/
void printList(Node* L, bool hasHead){
    Node* p;
    if(hasHead){
    	p = L->next;
	}else{
		p = L;
	}
    while(p!=NULL){
        cout<<p->num<<" ";
        p=p->next;
    }
    cout<<endl;
}
//上面的代码逻辑默认是包含头结点的,所以在代码中,我定义了p=L->next;

//这里给出一个工具函数:计算单链表的长度,因为很多地方需要用到,所以这里抽象出来了。
/*
    @Node*p 所需要计算长度的单链表
    @return 返回链表的长度
*/
int getListLength(Node* p, bool hasHead){
    int count = 0;
    while(p->next!=NULL){
        count++;
        p=p->next;
    }
    return hasHead?count:count+1;
}
#endif

猜你喜欢

转载自blog.csdn.net/qq_26460841/article/details/83217366
今日推荐