0
点赞
收藏
分享

微信扫一扫

单链表的逆置

问题描述

已知单链表h,写一算法将其倒置。


图解

单链表的逆置_链表

代码实现

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

typedef int ElemType;

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

InitList(LinkList &L) {
	L = (LNode*)malloc(sizeof(LNode));
	if (L == NULL)
		return false;
	L->next = NULL;
	L->data = 0;
	return true;
}


LinkList TailInsert(LinkList& L) {
	int x;
	LNode* s;
	LNode* r;
	r = L;
	scanf("%d", &x);
	while (x !=-1) {
		s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		s->next = r->next;
		r->next = s;
		r = s;
		scanf("%d", &x);
	}
	return L;
}

void Print(LinkList h)
{
	LinkList p;
	p = h->next;
	if (h == NULL)
	{
		printf("链表为空\n");
	}
	else
	{
		printf("链表如下:\n");
		while (p != NULL)
		{
			printf("%d ", p->data);
			p = p->next;
		}
	}
	printf("\n");
}


void ReserveInsert(LinkList& L) {
	LNode* s;
	LNode* r = L->next;
	L->next = NULL;
	while (r != NULL) {
		s = r;
		r = r->next;
		s->next = L->next;
		L->next = s;
	}
}



int main() {
	LinkList L;
	InitList(L);
	TailInsert(L);
	Print(L);
	printf("\n");
	ReserveInsert(L);
	Print(L);
	return 0;
}

运行结果

单链表的逆置_List_02

举报

相关推荐

0 条评论