利用单链表实现逆序输出

【程序代码】

#include<iostream>
using namespace std;

typedef struct LNode {
	char data;
	struct LNode *next;
} LNode,*LinkList;

void Reverse(LinkList &L,int n) {
	//生成头结点,用头指针L指向它
	L=new LNode;
	L->next=NULL;
	//头插法创建单链表
	for(int i=0; i<n; i++) {
		LinkList p;
		p=new LNode;
		cin>>p->data;
		p->next=L->next;
		L->next=p;
	}
	//输出单链表中结点的值
	while(L->next) {
		cout<<L->next->data<<" ";
		L->next=L->next->next;
	}
}

int main () {
	int n;
	cin>>n;
	LinkList LA;
	Reverse(LA,n); //输入n个字符,并逆序输出

	return 0;
}


/*
in:
8
F H 8 M 2 U 7 A

out:
A 7 U 2 M 8 H F
*/


  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以回答这个问题。 以下是用C语言实现从键盘输入正整数,利用尾插法形成单链表并输出的代码: ```c #include <stdio.h> #include <stdlib.h> // 定义单链表的结构体 typedef struct ListNode { int val; struct ListNode *next; } ListNode; // 尾插法建立单链表 ListNode* createList() { ListNode *head = NULL, *tail = NULL; int num; while (scanf("%d", &num) == 1 && num > 0) { ListNode *node = (ListNode*) malloc(sizeof(ListNode)); node->val = num; node->next = NULL; if (head == NULL) { head = tail = node; } else { tail->next = node; tail = node; } } return head; } // 输出单链表 void printList(ListNode* head) { while (head != NULL) { printf("%d ", head->val); head = head->next; } printf("\n"); } int main() { // 读入数据并建立单链表 printf("Please input integers separated by spaces, end with a non-positive integer:\n"); ListNode *head = createList(); // 输出单链表 printf("The linked list is:\n"); printList(head); return 0; } ``` 接下来是将输入的数据逆序建立单链表并输出的代码: ```c // 将单链表逆序 ListNode* reverseList(ListNode* head) { if (head == NULL || head->next == NULL) { return head; } ListNode *prev = NULL, *cur = head, *next = head->next; while (cur != NULL) { cur->next = prev; prev = cur; cur = next; if (next != NULL) { next = next->next; } } return prev; } int main() { // 读入数据并建立单链表 printf("Please input integers separated by spaces, end with a non-positive integer:\n"); ListNode *head = createList(); // 输出单链表 printf("The linked list is:\n"); printList(head); // 将单链表逆序 head = reverseList(head); // 输出逆序后的单链表 printf("The reversed linked list is:\n"); printList(head); return 0; } ``` 希望这个回答能够帮到你!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值