「數據結構」帶頭節點的單鏈表的基本操作

「數據結構」帶頭節點的單鏈表的基本操作

以下是帶頭節點的單鏈表的基本操作,以待日後查閱。

代碼展示

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define ERROR 0
#define OK 1

typedef int Status;
typedef int ElemType; 

typedef struct LNode{
	ElemType data;
	struct LNode *next;
} LNode, *LinkList;

創建(方法不同)

逆位序輸入

Status CreateList_L(LinkList &L, int n){
	// 逆位序輸入:輸入1,2,3 ==> 輸出3,2,1
	LNode *p;
	L=(LinkList)malloc(sizeof(LNode));
	L->next=NULL;
	for(int i=n; i>0; --i){
		p=(LinkList)malloc(sizeof(LNode));
		scanf("%d",&p->data);
		p->next=L->next;
		L->next=p;
	}
}

順序輸入

Status CreateList_L(LinkList &L, int n){
	// 順序輸入
	LNode *q;
	LNode *p; 
	L=(LinkList)malloc(sizeof(LNode));
	L->next=NULL;
	q=L;
	for(int i=0; i<n; ++i){
		p=(LinkList)malloc(sizeof(LNode));
		scanf("%d",&p->data);
		q->next=p;
		q=p;
	}
	q->next=NULL;
} 

輸出

Status PrintList_L(LinkList &L){
	LNode *p = L->next;
	while(p != NULL){
		printf("%d ", p->data);
   		p=p->next;
	}
	printf("\n"); 
}

就地逆置

/**
①將原來的頭結點拆下來,作爲新的逆置鏈表的頭結點
②將原來鏈表的各個節點,依次拆卸下來,然後按照頭插法,插入到逆置鏈表當中
③循環,直到原來的鏈表爲空即可。
**/ 

Status ReverseList_L(LinkList &L){
	LNode *p, *q;
	p=L->next;// ①將原來的頭結點拆下來,作爲新的逆置鏈表的頭結點 
	L->next=NULL;
	
	// 將原來鏈表的各個節點,依次拆卸下來,然後按照頭插法,插入到逆置鏈表當中 
	// 循環,直到原來的鏈表爲空即可。 
	while(p){
		q=p->next;
		p->next=L->next;
		L->next=p;// 向前插入 
		p=q;// 便於while循環去驗證有沒有做到頭 
	}
}

主函數

int main(){
	LinkList L;
	int n;
	printf("Length:");
	scanf("%d",&n);
	CreateList_L(L, n);
	PrintList_L(L);
	ReverseList_L(L);
	PrintList_L(L);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章