最少变量进行链表逆置,怕忘存档

栏目: 数据库 · 发布时间: 5年前

内容简介:简单的思路,就是首先交换但是

基本思路

简单的思路,就是首先交换 root->nextrevert_root 的指向,此时已经逆置了一个元素

但是 rootrevert_root 就反了,再交换下就 ok 了

直接上代码

/*
        Author: SpringHack - springhack@live.cn
        Last modified: 2019-04-02 01:32:40
        Filename: main.c
        Description: Created by SpringHack using vim automatically.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Test data
int test_data[] = {
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};

// Node struct
typedef struct _node {
  int value;
  struct _node* next;
} node_item;
// Just easy to use malloc
typedef node_item* node;

// Define linked list root and reverted linked list root
// Only two variables needed to revert a linked list
static node root = NULL;
static node revert_root = NULL;

int main() {
  // Create linked list
  {
    int i = 0, count = sizeof(test_data) / sizeof(int);
    node tmp;
    while (i < count) {
      if (!root) {
        root = (node)malloc(sizeof(node_item));
        tmp = root;
      } else {
        tmp->next = (node)malloc(sizeof(node_item));
        tmp = tmp->next;
      }
      tmp->next = NULL;
      tmp->value = test_data[i];
      ++i;
    }
  }
  // Print linked list
  {
    node tmp = root;
    while (tmp) {
      printf(tmp->next ? "%d " : "%d", tmp->value);
      tmp = tmp->next;
    }
    printf("\n");
  }
  // Revert linked list
  {
    while (root) {
      if (!revert_root) {
        revert_root = root;
        root = root->next;
        revert_root->next = NULL;
      } else {
        revert_root = (node)((intptr_t)revert_root ^ (intptr_t)root->next);
        root->next = (node)((intptr_t)revert_root ^ (intptr_t)root->next);
        revert_root = (node)((intptr_t)revert_root ^ (intptr_t)root->next);
        revert_root = (node)((intptr_t)revert_root ^ (intptr_t)root);
        root = (node)((intptr_t)revert_root ^ (intptr_t)root);
        revert_root = (node)((intptr_t)revert_root ^ (intptr_t)root);
      }
    }
  }
  // Print reverted linked list
  {
    node tmp = revert_root;
    while (tmp) {
      printf(tmp->next ? "%d " : "%d", tmp->value);
      tmp = tmp->next;
    }
    printf("\n");
  }
  return 0;
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Linux内核设计与实现(原书第3版)

Linux内核设计与实现(原书第3版)

Robert Love / 陈莉君、康华 / 机械工业出版社华章公司 / 2011-4-30 / 69.00元

《Linux内核设计与实现(原书第3版)》详细描述了Linux内核的设计与实现。内核代码的编写者、开发者以及程序开发人员都可以通过阅读本书受益,他们可以更好理解操作系统原理,并将其应用在自己的编码中以提高效率和生产率。 《Linux内核设计与实现(原书第3版)》详细描述了Linux内核的主要子系统和特点,包括Linux内核的设计、实现和接口。从理论到实践涵盖了Linux内核的方方面面,可以满......一起来看看 《Linux内核设计与实现(原书第3版)》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具