c++单向链表

#include <iostream>
#include <time.h>
using std::cout;
using std::endl;
struct Node
{
	int data;
	struct Node* next;
};

一、创建链表

Node * createList()
{
	Node *head = new Node;
	if (NULL == head)
		exit(-1);
	head->next = NULL;
	return head;
}

二、尾插法
在这里插入图片描述

void inisertListTail(Node *head, int num) 
{
	while (head->next!= NULL)
	{
		head = head->next;
	}
	Node *t = head;
	Node *cur = new Node;
	if (NULL == cur)
		exit(-1);
	cur->data = num;
	t->next = cur;
	t = cur;
	t->next = NULL;
}

二、头插法
在这里插入图片描述

void insertListHead(Node *head, int nums)
{
	Node *cur = new Node;
	if (NULL == cur)
		exit(-1);
	cur->data = nums;
	cur->next = head->next;
	head->next = cur;
}

三、求链表长度

int lengthList(Node *head)
{
	head = head->next;
	int i = 0;
	while (head)
	{
		head = head->next;
		i++;
	}
	return i;
}

四、查找

Node *searchList(Node *head, int findData)
{
	head = head->next;
	while (head)
	{
		if (head->data == findData)
			break;
		head = head->next;
	}
	return head;
}

五、删除
在这里插入图片描述

void deleteData(Node *head, Node *pfind)
{
	if (pfind->next == NULL)
	{
		while (head->next != pfind)     //方法1  找到前一个
		{
			head = head->next;
		}
		head->next = pfind->next;
		delete(pfind);
		pfind = NULL;
	}
	else
	{
		Node *t = pfind->next;
		pfind->data = pfind->next->data; //优化后(替换)
		pfind->next = pfind->next->next;
		delete(t);
	}
}

六、排序(换值)

void popSortList(Node *head)    //交换数据
{
	int n=0;
	head = head->next;
	Node *t = NULL;
	int nums = lengthList(head);
	for (int i = 0;i < nums - 1;i++)
	{
		t = head;
		for (int j = 0;j < nums - 1 - i;j++)
		{
			if (t->data < t->next->data)
			{
				n = t->data;
				t->data = t->next->data;
				t->next->data = n;
			}
			t = t -> next;
		}
	}
}

排序(换指针)
在这里插入图片描述

void popSortList2(Node *head)
{
	Node *prep = NULL;
	Node *p = NULL;
	Node *q=NULL;
	Node *t = NULL;
	int nums = lengthList(head);
	for (int i = 0;i < nums - 1;i++)
	{
		prep = head;
		p = head->next;
		q = p->next;
		for (int j = 0;j < nums - 1 - i;j++)
		{
			if (p->data > q->data)
			{
				prep->next = q;
				p->next = q->next;
				q->next = p;

				t = q;
				q = p;
				p = t;
			}
			prep = prep->next;
			p = p->next;
			q = q->next;
		}
	}
}

七、链表逆置
在这里插入图片描述

void reverseList(Node *head)
{
	Node *t = NULL;
	head->next = NULL;//将链表分为两部分。
	Node *cur = head->next;
	while (cur)
	{
		t = cur;
		cur = cur->next;
		t->next = head->next;
		head->next = t;		
	}
}

八、删除链表

void deleteList(Node *head)
{
	Node *t = NULL;
	while (head)
	{
		t = head->next;
		delete(head);
		head = t;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42972267/article/details/85930359