将不带头节点的单向链表节点数据域中的数据从小到大排序,即若圆链表节点数据域从头至尾的数据为10 4 2 8 6,排序后链表节点数据域从头至尾的数据为2 4 6 8 10。
供参考:
void sortList(NODE *h)
{
/************Begin**********/
int t;
NODE *ph = NULL, *pt = NULL;
ph = h;
while (ph)
{
pt = ph->next;
while (pt)
{
if (ph->data > pt->data)
{
t = ph->data;
ph->data = pt->data;
pt->data = t;
}
pt = pt->next;
}
ph = ph->next;
}
/************End**********/
}
void sortList(NODE* h)
{
NODE* current;
NODE* index;
int temp;
if (h == NULL || h->next == NULL)
{
return;
}
current = h->next;
while (current != NULL)
{
index = current->next;
while (index != NULL)
{
if (current->data > index->data)
{
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
#include <bits/stdc++.h>
using namespace std;
int a[105][105],n,num;
int main(){
cin>>n;
for(int i=0;i<n;i++)
{
if(i%2==0)
for(int j=0;j<n;j++)
num++,a[i][j]=num;
else
for(int j=n-1;j>=0;j--)
num++,a[i][j]=num;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
return 0;
}
问题回答:
要对链表的节点进行排序,可以使用常见的排序算法,比如选择排序、冒泡排序或插入排序等。下面以选择排序为例来说明具体的解决方案:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def swap_nodes(prev_node, node1, node2):
if node1 == node2:
return
if prev_node:
prev_node.next = node2
else:
head = node2
temp = node2.next
node2.next = node1
node1.next = temp
def selection_sort(head):
if not head:
return head
cur = head
while cur:
min_node = cur
next_node = cur.next
while next_node:
if next_node.data < min_node.data:
min_node = next_node
next_node = next_node.next
swap_nodes(cur, cur, min_node)
cur = cur.next
return head
def create_linked_list(values):
head = Node(None)
cur = head
for value in values:
cur.next = Node(value)
cur = cur.next
head = head.next
return head
values = [10, 4, 2, 8, 6]
head = create_linked_list(values)
sorted_head = selection_sort(head)
result = []
cur = sorted_head
while cur:
result.append(cur.data)
cur = cur.next
print(result) # 输出: [2, 4, 6, 8, 10]
通过以上步骤,我们成功地将链表中的节点按照数据域的大小进行排序。如果要使用其他排序算法,可以相应地修改交换节点位置的逻辑,但整体思路是类似的。
数据结构对单链表进行数据排序 http://bbs.csdn.net/topics/392201633