#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;
}
反轉鏈表-C語言
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.