單鏈表逆序(c實現)

單鏈表逆序作爲常見的數據操作,具體實現有不同的版本,但是總歸需要考慮輸入結點爲空、一個結點和多個結點的情況。

該逆序思想來自《劍指offer》;另外一個容易想到的逆序方式是,申請一個頭結點head,然後把待逆序結點順序插入到頭結點後head->next,最後返回head->next即可。

#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
	int data;
	struct Node *next;
} Node;
Node* create_list(int *array,const int length)
{
	if(array==NULL)
	{
		return NULL;
	}
	if(length<=0)
	{
		return NULL;
	}
	Node *head = (Node*)malloc(sizeof(Node));
	head->data =  array[0];
	head->next = NULL;
	Node *p ,*q = head;
	for(int i=1;i<length;i++)
	{
		p = (Node*)malloc(sizeof(Node));
		p->data = array[i];
		q->next = p;
		q = p;
	}
	q->next = NULL;
	return head;
}
Node *reverse(Node *head)
{
	//     1 --> 2 --> 3 --> 4 -->... --> NULL
	//        
	//NULL <-- 1 <-- 2     3 --> 4 -->... --> NULL
	//       prev   cur   next
	Node *prev; //指向已逆序的頂端
	Node *cur;  //指向待逆序的首端
	Node *next; //指向待逆序的首端的下一個結點
	if(head==NULL)
	{
		return NULL;
	}
	cur = head->next;
	prev = head;
	prev->next = NULL; //頭結點變尾結點,next置空
	while(cur!=NULL)
	{
		next = cur->next;
		cur->next = prev;
		prev = cur;
		cur = next;
	}
	return prev;
}
void print(Node *head)
{
	Node *p = head;
	while(p!=NULL)
	{
		fprintf(stdout,"%d ",p->data);
		p = p->next;
	}
}
int main(void)
{
	int a[] = {3,5,6,7,7,83,23};
	const int len = sizeof(a)/sizeof(int);
	Node *head = create_list(a,len);
	print(head);
	printf("\n");
	Node *rev = reverse(head);
	print(rev);
	printf("\n");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章