1. 程式人生 > >只遍歷一次,將單鏈表中的元素順序反轉過來

只遍歷一次,將單鏈表中的元素順序反轉過來

轉載請註明出處。

思想很簡單,邊遍歷邊將指標反向,順便將資料往前移一個單位,這樣原來的最後一個節點就變成頭節點了。

程式碼實現如下:

#include<stdio.h>
#include<malloc.h>

typedef struct LNode {
	int data;
	struct LNode *next;
}LNode,*linkList;

linkList creatLinkList(int n) {//建立一個含n個元素的單鏈表
	linkList head = (linkList)malloc(sizeof(LNode));
	linkList p,q;
	head->data = n;//記錄連結串列中元素個數
	q = head;
	for(int i = 0;i < n;i++) {
		p = (linkList)malloc(sizeof(LNode));
		scanf("%d",&p->data);
		q->next = p;
		q = p;
	}
	q->next = NULL;
 	return head;
}

void listTraverse(linkList q) {
	while(q->next) {
		printf("%d ",q->next->data);
		q = q->next;
	}
}

linkList reverseLinkList(linkList head) {
	linkList q= head->next,p = NULL;
	head->next = NULL;
	while(q)
	{
		head->data = q->data;//先改資料,反正對指標指向無影響 
		p = q->next;//q->next要轉向用p暫存 
		q->next = head;//q->next轉向 
		head= q;//head,q向後移動一位 
		q = p;
	} 
	return head;
}

int main() {
	linkList head = creatLinkList(5);//建立一個含5個元素的單鏈表
	printf("建立後遍歷:\n");
	listTraverse(head);
	printf("\n單鏈錶轉置後:\n");
	head = reverseLinkList(head);
	listTraverse(head);
	printf("\n");
}