反轉鏈表

反轉鏈表:
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;
}        
發佈了19 篇原創文章 · 獲贊 3 · 訪問量 1856
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章