单向链表基本操作的实现

单链表是数据结构知识体系中承上启下的部分,掌握单链表的创建、遍历、排序、插入等基本操作,对下面学习栈、队列、树、图起着非常重要的作用。

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int data; //数据域
    struct Node * pNext; //指针域
}NODE,*PNODE;

//函数定义
//创建
PNODE createList(void)
{
    int len; //存放有效结点的个数
    int i;
    int val; //临时存放结点的值
    
    //分配一个不存放数据的头结点
    PNODE pHead = (PNODE)malloc(sizeof(NODE));
    if (pHead == NULL)
    {
        printf("动态内存分配失败,程序终止!");
        exit(-1);
    }
    PNODE pTail = pHead;
    pTail->pNext = NULL;
    
    printf("输入你要生成的链表结点的个数:");
    scanf("%d",&len);
    
    for (i=0; i<len; i++)
    {
        printf("请输入第%d个结点的值:",i+1);
        scanf("%d",&val);
        PNODE pNew = (PNODE)malloc(sizeof(NODE));
        if (pNew == NULL)
        {
            printf("动态内存分配失败,程序终止!");
            exit(-1);
        }
        pNew->data = val;
        pTail->pNext = pNew;
        pNew->pNext = NULL;
        pTail = pNew;
    }
    
    return pHead;
}

//遍历
void traverseList(PNODE pHead)
{
    PNODE p = pHead->pNext;
    
    while (p!=NULL)
    {
        printf("%d ",p->data);
        p = p->pNext;
    }
    printf("\n");
    return;
}

//判断是否为空
bool isEmpty(PNODE pHead)
{
    if (pHead->pNext == NULL)
    {
        return true;
    }
    else
    {
        return false;
    }
}

//求链表长度
int lengthList(PNODE pHead)
{
    PNODE p = pHead->pNext;
    int len = 0;
    while (p != NULL)
    {
        len++;
        p = p->pNext;
    }
    return len;
}

//链表排序
void sortList(PNODE pHead)
{
    int t;
    PNODE p,q;
    for (p = pHead->pNext; p->pNext != NULL; p = p->pNext)
    {
        for (q = p->pNext; q != NULL; q = q->pNext)
        {
            if (p->data > q->data)
            {
                t = p->data;
                p->data = q->data;
                q->data = t;
            }
        }
    }
    
    return;
}

//在pHead所指向链表的第pos个结点的前面插入一个新的结点,该结点的值是val, 并且pos的值是从1开始
bool insertList(PNODE pHead, int pos, int val)
{
    int i = 0;
    PNODE p = pHead;
    
    while (p != NULL && i<pos-1)
    {
        p = p->pNext;
        i++;
    }
    
    if (i>pos-1 || p ==NULL) //排除pos<=0和pos过大的情况
        return false;
    
    //如果程序能执行到这一行说明p已经指向了第pos-1个结点,但第pos-1个结点是否存在无所谓
    PNODE pNew = (PNODE)malloc(sizeof(NODE));
    if (pNew == NULL)
    {
        printf("动态分配内存失败!\n");
        exit(-1);
    }
    pNew->data = val;
    
    //执行插入操作
    pNew->pNext = p->pNext;
    p->pNext = pNew;
    
    return true;
}

//删除结点
bool deleteList(PNODE pHead, int pos, int * pVal) //pVal用于获取被删除结点数据域的值
{
    int i = 0;
    PNODE p = pHead;
    
    while (p->pNext != NULL && i<pos-1)
    {
        p = p->pNext;
        i++;
    }
    
    if (i>pos-1 || p->pNext == NULL)
        return false;
    
    PNODE q = p->pNext; //q指向待删除的结点
    p->pNext = p->pNext->pNext;
    
    *pVal = q->data;
    free(q);
    q = NULL;
    
    return true;
} 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注