单链表应用

问题描述:1、设计一个算法,将一个带头结点的数据域依次为a1,a2,…,an(n≥3)的单链表的所有结点逆置, 

                          即第一个结点的数据域变为an,…,最后一个结点的数据域为a1。实现这个算法,并完成测试。 

                        输入描述:若干数据 。     

                        程序输出:链表中的数据及逆序拍好后的数据。  


 

#include"linklist.h"
int main()
{
    linklist *L;
    ElemType a[]= {1,3,5,7, 2,4,8,10};
    CreateListR(L,a,8);
    printf("L:");
    DispList(L);
    Reverse(L);
    printf("逆置后L: ");
    DispList(L);
    DestroyList(L);
    return 0;
}


 

 

void Reverse(linklist *l)
{
	linklist *p,*q;
	p=l->next;
	l->next=NULL;
	while(p!=NULL)
	{
		q=p->next;
		p->next=l->next;
		l->next=p;
		p=q;
	}

}


 结果为:

 

 

 

 

以下是一个简单的单链表应用实例代码,使用C语言实现: ```c #include <stdio.h> #include <stdlib.h> // 定义链表结构体 typedef struct Node { int data; struct Node* next; } node; // 创建新节点 node* create_node(int data) { node* new = (node*)malloc(sizeof(node)); new->data = data; new->next = NULL; return new; } // 在链表末尾插入节点 void insert_node(node** head, int data) { node* new = create_node(data); if (*head == NULL) { *head = new; return; } node* current = *head; while (current->next != NULL) { current = current->next; } current->next = new; } // 删除指定值的节点 void delete_node(node** head, int data) { if (*head == NULL) { return; } if ((*head)->data == data) { node* temp = *head; *head = (*head)->next; free(temp); return; } node* current = *head; while (current->next != NULL && current->next->data != data) { current = current->next; } if (current->next != NULL) { node* temp = current->next; current->next = current->next->next; free(temp); } } // 打印链表 void print_list(node* head) { printf("Linked List: "); while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); } int main() { node* head = NULL; insert_node(&head, 1); insert_node(&head, 2); insert_node(&head, 3); insert_node(&head, 4); insert_node(&head, 5); print_list(head); delete_node(&head, 3); print_list(head); delete_node(&head, 1); print_list(head); return 0; } ``` 该代码实现了一个单链表的基本操作,包括创建节点、在末尾插入节点、删除指定值的节点和打印链表。可以通过在 `main` 函数中调用这些函数来使用这个单链表
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值