反转链表-C语言

mac2022-06-30  145

#include <stdio.h> #include <stdlib.h> /* 大型工程上用于随时调试或者注释掉 */ /* 想要注释直接改 _DEBUG为其他如_DEBUGG */ #define _DEBUG #undef PDEBUG #ifdef _DEBUG #define PDEBUG(fmt, args...) printf(fmt, ##args) #else #define PDEBUG(fmt, args...) #endif /* 定义链表节点 */ typedef struct node{ int data; struct node *next; }Node; /* 创建链表节点 */ Node *creatnode(int num) { Node *p = (Node *)malloc(sizeof(Node)); p->data = num; p->next = NULL; return p; } /* 创建单向链表 */ Node *creatlist(int arr[], int length) { Node *head, *p, *tail; int len = length; int i; for(i=0; i<len; i++) { p = creatnode(arr[i]); if(0 == i) head = p; else tail->next = p; tail = p; } tail->next = NULL; return head; } /* 反转链表 */ Node *reverslist(Node *head) { Node *pre = head; Node *cur = head->next; Node *tmp = head->next->next; while( cur ) { tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } head->next = NULL; return pre; } /* 打印链表 */ void display(Node *head) { Node *p=head; while( p ) { PDEBUG("%d->", p->data); p = p->next; } PDEBUG("\n"); } int main(void) { int arr[] = {0, 1, 3, 5, 7, 9, 10, 12}; int length = sizeof(arr)/sizeof(arr[0]); Node *s = creatlist(arr, length); display(s); return 0; }
最新回复(0)