C++链表操作
1.链表的冒泡排序
2.翻转链表
3.查找链表中间节点
4.删除倒数第K个链表
操作效果如下
代码
#include <iostream>
#include <algorithm>
using namespace std;
void bubble_sort(int a[], int N)
{
int i = N - 1;
while (i > 0)
{
int lastex = 0;
for (int j = 0; j < i; j++)
{
if (a[j]>a[j + 1])
{
swap(a[j], a[j + 1]);
lastex = j;
}
}
i = lastex;
}
}
struct Node{
int data;
Node *next;
};
int main()
{
int arr[] = { 4, 3, 5, 2, 1 };
//插入链表
Node *head, *prev;
head = NULL;
prev = head;
for (int i = 0; i < 5; i++)
{
Node *temp = new Node;
temp->data = arr[i];
temp->next = NULL;
if (head == NULL)
head = temp;
else
prev->next = temp;
prev = temp;
}
cout << "原始链表-----" << endl;
Node *cur = head;
while (cur != NULL)
{
cout << cur->data << "-";
cur = cur->next;
}
cout << endl;
//冒泡排序
Node *end = NULL;
while (end != head)
{
cur = head;
while (cur->next != end)
{
if (cur->data > cur->next->data)
{
int temp = cur->next->data;
cur->next->data = cur->data;
cur->data = temp;
}
cur = cur->next;
}
end = cur;
}
cout << "冒泡排序后-----" << endl;
cur = head;
while (cur != NULL)
{
cout << cur->data << "-";
cur = cur->next;
}
cout << endl;
//翻转链表
Node *new_head = NULL;
while (head != NULL)
{
cur = head;
head = head->next;
if (new_head == NULL)
{
new_head = cur;
new_head->next = NULL;
}
else
{
cur->next = new_head;
new_head = cur;
}
}
head = new_head;
cout << "翻转链表后-----" << endl;
cur = head;
while (cur != NULL)
{
cout << cur->data << "-";
cur = cur->next;
}
cout << endl;
//查找中间节点
Node *fast, *slow;
fast = slow = head;
while (fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
cout << "中间节点-----" << endl;
cout << slow->data << endl;
//删除倒数第k=3个节点
Node *front, *back;
front = back = head;
front = front->next->next;
while(front->next != NULL)
{
front = front->next;
back = back->next;
}
back->data = back->next->data;
Node *del = back->next;
back->next = back->next->next;
delete del;
del = NULL;
cout << "删除倒数第k=3个节点后-----" << endl;
cur = head;
while (cur != NULL)
{
cout << cur->data << "-";
cur = cur->next;
}
cout << endl;
return 0;
}