单链表倒序的实现

目录

 

单链表

链表倒序的实现思想 

实现代码 


  • 单链表

  • 链表倒序的实现思想 

由于单链表从尾部到头部的顺序遍历比较难以实现,我们可以利用数据结构学的栈来实现,即链表的头部开始依次遍历链表的每一个数据元素,然后再一次将每一个链表的数据依次入栈,完事儿再一次出栈,就可以简单的实现链表的倒序。

  • 实现代码 

#include <iostream>

using namespace std;
typedef int Elementtype;
typedef struct st_link
{
	Elementtype data;
	struct st_link* next;
}ListNode;

ListNode* Create_link(Elementtype data, int num)  //创建链表
{
	ListNode* head;
	ListNode* newnode;
	ListNode* curnode = NULL;

	head = (ListNode*)malloc(sizeof(ListNode));
	head->data = -1;
	head->next = NULL;

	for (int i = 0; i < num; ++i)
	{
		newnode = (ListNode*)malloc(sizeof(ListNode));
		if (NULL == head->next)
		{
			newnode->data = data + i;
			newnode->next = NULL;
			curnode = newnode;
			head->next = newnode;
		}
		curnode->next = newnode;
		newnode->data = data + i;
		newnode->next = NULL;
		curnode = newnode;
	}
	return head;
}

int* Push_stack(ListNode* head) //入栈&出栈
{
	if (NULL == head)
	{
		return NULL;
	}

	int top = 0;
	int size = 0;
	ListNode* tmp = head;
	while (tmp->next != NULL)
	{
		++size;
		tmp = tmp->next;
	}
	cout << size << endl;
	int *arr =new int[size*8];
	if (head->next != NULL)
	{
		while (head->next != NULL)
		{
			arr[top] = head->data;
			top += 1;
			head = head->next;

		}
	}
	else 
		arr[top] = head->data;
	while (top > 0)
	{
		cout << arr[top-1] << endl;
		top--;
	}
	return arr;
}
void test()
{
	int* Itmp = NULL;
	ListNode* tmp = Create_link(10,100);
	Itmp = Push_stack(tmp);
}

int main()
{
	test();
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/qq_44045338/article/details/106359795