c++链表,含链表的构造,删除某链表节点,和链表冒泡排序

#include 
using namespace std;

class listnode
{
public:
	int val;
	listnode* next;

public:
	listnode(int val)
	{
		this->val = val;
		this->next = NULL;
	}
};

listnode* createlistnode(int* arr, int num)
{
	if (num == 0)
		return nullptr;

	listnode* head = new listnode(0);//头节点不存数据
	listnode* ahead = head, * back = head;
	for(int i=0;inext = ahead;
	}
	return head;
}


listnode* deletelistnode(listnode* head, int val)
{
	listnode* ahead = head->next, * back = head;
	while (ahead)
	{
		if (ahead->val == val)
		{
			back->next = ahead->next;
			free(ahead);
			ahead = back->next;
			continue;
		}

		back = back->next;
		ahead = ahead->next;

	}
	return head;
}

void printlistnode(listnode* head)
{
	listnode* ptr = head->next;
	while (ptr)
	{
		cout << ptr->val << " ";
		ptr = ptr->next;
	}
}

listnode* bubulesort(listnode* head)
{


	//先遍历去找节点个数(头节点不算)
	listnode* ptr = head->next;
	int count = 0;
	while (ptr)
	{
		count++;
		ptr = ptr->next;
	}
	listnode* ahead = head->next->next;
	listnode* back = head->next;
	listnode* temp = head;

	for (int j = 0; j < count - 1; j++)
	{
		int num = count - 1 - j;
		listnode* ahead = head->next->next;
		listnode* back = head->next;
		listnode* temp = head;
		for (int k = 0; k < num; k++)
		{
			if (back->val > ahead->val)
			{
				back->next = ahead->next;
				ahead->next = back;
				temp->next = ahead;
			}
			listnode* swap = back;
			back = ahead;
			ahead = swap;

			ahead = ahead->next;
			back = back->next;
			temp = temp->next;
		}
	}
	return head;

	
}

int main()
{
	int arr[10] = { 10,9,8,7,6,5,4,3,2,1 };
	listnode* head = createlistnode(arr, 10);
	head = deletelistnode(head, 3);
	head = bubulesort(head);
	printlistnode(head);
	return 0;
}


你可能感兴趣的:(链表,c++,数据结构,链表冒泡排序)