博客
关于我
单链表按序号奇偶分链表
阅读量:282 次
发布时间:2019-03-01

本文共 1470 字,大约阅读时间需要 4 分钟。

单链表按序号奇偶分割成两个子链表的实现

本文将介绍如何将一个带头结点的单链表按照序号的奇偶性分割成两个子链表headAheadB,并保持原有节点的顺序不变。

代码分析与实现

1. 创建链表

首先,我们需要创建一个链表。以下是创建链表的关键代码:

LinkList* CreaList() {    LinkList* head, *r, *s;    head = (struct LinkList*)malloc(sizeof(struct LinkList));    r = head;    int x;    scanf("%d", &x);    while (x != -100) {        s = (struct LinkList*)malloc(sizeof(struct LinkList));        s->data = x;        r->next = s;        r = s;        scanf("%d", &x);    }    r->next = NULL;    return head;}

2. 链表分割

接下来,我们需要将链表按照序号的奇偶性分割成两个子链表headAheadB。以下是实现代码:

LinkList* Selet(LinkList* head) {    LinkList* r, *s, *cur;    int i = 0;    LinkList* headB = (struct LinkList*)malloc(sizeof(struct LinkList));    r = head;    s = headB;    cur = head->next;    r->next = NULL;    while (cur != NULL) {        i++;        if (i % 2 != 0) {            r->next = cur;            r = cur;        } else {            s->next = cur;            s = cur;        }        cur = cur->next;    }    r->next = NULL;    s->next = NULL;    return headB;}

3. 打印链表

最后,我们需要打印链表。以下是打印函数:

void PrintList(LinkList* head) {    LinkList* p = head;    p = p->next;    while (p != NULL) {        printf("%d ", p->data);        p = p->next;    }    printf("\n");    return 0;}

主函数实现

int main() {    LinkList* head, *headA, *headB;    head = CreaList();    PrintList(head);    headB = Selet(head);    PrintList(head);    PrintList(headB);    return 0;}

总结

通过以上实现,我们可以轻松地将一个带头结点的单链表按照序号的奇偶性分割成两个子链表headAheadB,并保持原有节点的顺序不变。

转载地址:http://ijho.baihongyu.com/

你可能感兴趣的文章
python redis 集群_python 搭建redis集群
查看>>
python redis连接,在Python中使用Redis连接池的正确方法
查看>>
python regex_Python RegEx
查看>>
python requests post 中文结果请求得到unicode
查看>>
Python Requests接口自动化测试实战
查看>>
Python requests模块
查看>>
python request与grequests该如何选择
查看>>
python request模块
查看>>
Python requirements.txt的使用方法
查看>>
Python REST(Web 服务)框架的推荐?
查看>>
Python rsa 加密
查看>>
Python RSA操作
查看>>
Python轻松实现统计学中重要的相关性分析
查看>>
Python scrapy 常见问题及解决 【遇到的坑】
查看>>
Python Seborn热图数据的动态更新
查看>>
Python Seborn绘制空白直方图
查看>>
Python Selenium - 获取href值
查看>>
Python Selenium实现自动化测试及Chrome驱动使用!
查看>>
Python Selenium搭建UI自动化测试框架
查看>>
Python Selenium模块详解
查看>>