单链表反转

链表有以下三个数据组成



程序:

#include "iostream"
#include<unordered_set>
#include<algorithm>
#include <malloc.h>
using namespace std;

typedef struct list
{
	int data;
	struct list* next;
}List, *p_List;
//创建一个链表
p_List creatList()
{
	p_List head_list = (p_List)malloc(sizeof(List));
	head_list->next = NULL;
	return head_list;
}

//前插
void insertFront(p_List head_list, int data)
{
	//创建新结点
	p_List new_node = (p_List)malloc(sizeof(List));
	new_node->data = data;
	new_node->next = NULL;
	//与头结点连接
	new_node->next = head_list->next;
	head_list->next = new_node;
}
//尾插
void insertTail(p_List head_list, int data)
{
	//创建新结点
	p_List new_node = (p_List)malloc(sizeof(List));
	new_node->data = data;
	new_node->next = NULL;

	p_List tmp = head_list;
	while (tmp->next)
	{
		tmp = tmp->next;
	}
	tmp->next=new_node;
	tmp = new_node;
}
//打印
void printList(p_List list1)
{
	list1 = list1->next;
	while (list1)
	{
		cout << list1->data << endl;
		list1 = list1->next;
	}
}
//在指定位置插一个结点
void insertPosition(p_List head_list,int data,int pos)
{
	//创建新结点
	p_List new_node = (p_List)malloc(sizeof(List));
	new_node->data = data;
	new_node->next = NULL;

	p_List p=head_list->next;
	int i = 0;
	while (i < pos - 1)
	{
		p = p->next;
		i++;
	}
	new_node->next = p->next;
	p->next = new_node;
}
//在指定位置删除一个结点
void deleteNode(p_List head_list, int pos)
{
	p_List p = head_list->next;
	p_List q;
	int i = 0;
	while (i < pos - 1)
	{
		p = p->next;
		i++;
	}
	q = p->next;
	p->next = q->next;
	free(q);
	q = NULL;
}
//链表反转
p_List inverseList(p_List head_list)
{
	p_List current, pnext, prev;
	current = head_list->next;
	pnext = current->next;
	current->next = NULL;
	while (pnext)
	{
		prev = pnext->next;
		pnext->next = current;
		current = pnext;
		pnext = prev;
	}
	head_list->next = current;
	return head_list;
}

int main()
{
	cout << "头插" << endl;
	p_List list1 = creatList();
	insertFront(list1, 1);
	insertFront(list1, 2);
	insertFront(list1, 3);
	printList(list1);
	cout << "指定位置插入" << endl;
	insertPosition(list1,4,1);
	printList(list1);
	cout << "指定位置删除" << endl;
	deleteNode(list1, 1);
	printList(list1);
	cout << "反转链表" << endl;
	p_List head_inverse;
	head_inverse = inverseList(list1);
	printList(head_inverse);
	cout << "....................................." << endl;
	cout << "尾插" << endl;
	p_List list2 = creatList();
	insertTail(list2, 1);
	insertTail(list2, 2);
	insertTail(list2, 3);
	printList(list2);
	return 0;
}
全部评论

相关推荐

身边有人上海、深圳&nbsp;6、7k&nbsp;都去了,真就带薪上班了。
程序员小白条:木的办法, 以后越来越差,还是家附近宅着吧,毕业的人越来越多,岗位都提供不出来,经济又过了人口红利期
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务