帮我用c语言写一个链表程序,并将输入的若干整数排序并输出
时间: 2023-06-06 09:07:52 浏览: 110
好的,这是一个关于C语言编写链表的程序,可以帮助您实现输入若干整数并排序的操作。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode{
int val;
struct ListNode *next;
}ListNode;
ListNode *insert(ListNode *head, int val){
ListNode *p = (ListNode*)malloc(sizeof(ListNode));
p -> val = val;
p -> next = head;
return p;
}
void printList(ListNode *head){
ListNode *p = head;
while(p){
printf("%d ", p -> val);
p = p -> next;
}
}
ListNode *sortList(ListNode *head){
if(head == NULL || head -> next == NULL) return head;
ListNode *slow = head;
ListNode *fast = head;
ListNode *prev = NULL;
while (fast && fast -> next){
prev = slow;
slow = slow -> next;
fast = fast -> next -> next;
}
prev -> next = NULL;
ListNode *l1 = sortList(head);
ListNode *l2 = sortList(slow);
return merge(l1, l2);
}
ListNode* merge(ListNode *l1, ListNode *l2){
ListNode *dummy = (ListNode*)malloc(sizeof(ListNode));
ListNode *p = dummy;
while(l1 && l2){
if(l1 -> val < l2 -> val){
p -> next = l1;
l1 = l1 -> next;
}
else{
p -> next = l2;
l2 = l2 -> next;
}
p = p -> next;
}
if(l1) p -> next = l1;
if(l2) p -> next = l2;
return dummy -> next;
}
int main(){
ListNode *head = NULL;
int n, val;
printf("请输入整数个数:\n");
scanf("%d", &n);
printf("请输入%d个整数:\n", n);
for(int i = 0; i < n; i++){
scanf("%d", &val);
head = insert(head, val);
}
printf("排序前:\n");
printList(head);
head = sortList(head);
printf("\n排序后:\n");
printList(head);
printf("\n");
return 0;
}
```
这个程序通过分离链表,递归排序,和链表归并操作来实现对输入的整数排序。希望能够对您有所帮助。
阅读全文