链表的排序和逆序

完整代码如下:

#include <stdio.h>
#include <malloc.h>
#include <windows.h>
#include <time.h>
#include <stdlib.h>

struct node {
 int data;
 struct node *next;
};

struct node *init_list(int num)
{
 struct node *h = NULL, *t = NULL;
 srand((unsigned)time(NULL));
 while (num-- > 0) {
  struct node *n = calloc(1, sizeof(struct node));
  n->data = rand();
  n->next = NULL;
  if (!h) {
   h = n;
   t = n;
  } else {
   t->next = n;
   t = n;
  }
 }
 return h;
}

void deinit_list(struct node *head)
{
 while (head) {
  struct node *prev = head;
  head = head->next;
  free(prev); prev = NULL;
 }
}

void print_list(struct node *head)
{
 while (head) {
  printf("%d ", head->data);
  head = head->next;  
 }
 printf("\n");
}

struct node *insert_list(struct node *head, struct node *n)
{
 struct node *h = NULL;
 if (head) {
  if (n->data < head->data) {
   h = n;
   n->next = head;
  } else {    
   struct node *prev = head;
   h = head;
   while (head = head->next) {
    if (n->data < head->data) {
     prev->next = n;
     n->next = head;
     return h;
    }
    prev = head;
   }
   prev->next = n;
   n->next = NULL;
  }
 } else {
  h = n;
  n->next = NULL;
 }
 return h;
}

struct node *order_list(struct node *head)
{
 struct node *h = NULL;
 while (head) {
  struct node *t = head;
  head = head->next;
  h = insert_list(h, t);  
 }
 return h;
}

//这里用递归法来实现逆序,返回的是尾节点, pHEAD是指向链表头节点的指针的地址,用地址传递得到它,很重要

struct node *reverse_list_recursive(struct node *head, struct node **pHEAD)
{
 struct node *t = head;
 if (head = head->next) {
  struct node *TAIL = reverse_list_recursive(head, pHEAD);
  TAIL->next = t;
  t->next = NULL;
  return t;
 } else {
  *pHEAD = t;
  return t;
 }
}

//这里用交换指针的方法来实现,看起来更简单
//会写程序不难,难的是写出好的程序,哈哈
struct node *reverse_list(struct node *head)
{
 struct node *prev = NULL;
 while (head) {
  struct node *next = head->next;
  head->next = prev;
  prev = head;
  head = next;
 }
 return prev;
}

void main()
{
 struct node *list = init_list(10);
 print_list(list);
 list = order_list(list);
 print_list(list);
 list = reverse_list(list);
 print_list(list);
 deinit_list(list);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值