反转链表:
1->2->3->4->5->NULL
反转后:
5->4->3->2->1->NULL
/* 链表结构 */
typedef struct node{
int val;
struct node *next;
}ListNode;
/* 反转单向链表 */
ListNode *reverlist(ListNode *head)
{
ListNode *pre = NULL;
ListNode *cur = head;
ListNode *tmp = cur;
while( cur != NULL )
{
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
完整代码:
#include <stdio.h>
#include <stdlib.h>
#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 = NULL;
Node *cur = head;
Node *tmp = cur;
while( cur )
{
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
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;
}