C 언어 링크

오랫동안 C 를 쓰 지 않 았 는데, 기본 기 를 잃 어 버 리 면 안 돼!오늘 하나 쓰 세 요.
#include <stdio.h>
#include <malloc.h>

typedef struct { //     
	int x;
	struct LNode *next;	
}LNode, *LPointer;


typedef struct { //     
	LPointer StartPoiner;
	LPointer EndPointer;
	int Length;	
}LinkList, *LinkListP;

int InitLinkList(LinkListP L) { //     ,        
	L->StartPoiner = (LPointer)malloc(sizeof(LNode));
	if (!L->StartPoiner) {
		return -1;
	}
	else {
		L->StartPoiner->x = 0x7fffffff;
		L->StartPoiner->next = NULL;
		L->EndPointer = L->StartPoiner;
		L->Length = 0;
		return 1;
	}
}

int InsertNode(LinkListP L, LNode mLNode) { //    mLNode 
	LPointer p = (LPointer)malloc(sizeof(LNode));
	if (!p) {
		return -1;
	}
	else {
		p->x = mLNode.x;
		p->next = NULL;
		L->EndPointer->next = p;
		L->EndPointer = p;
		L->Length++;
		return 1;	
	}
}

int DelNode(LinkListP L, int position) { //  position     ,1<=position<=L->Length 
	if (position > L->Length || position < 1) return -1;
	else {	
		LPointer p = L->StartPoiner;
		int count = 1;
		while (p != NULL && count < position) {
			count++;
			p = p->next;
		}
		LPointer pdel = p->next;
		p->next = pdel ->next;
		L->Length--;
		free(pdel);
		return 1;
	}
}

LPointer getNode(LinkListP L, int position) { //  position     ,1<=position<=L->Length  
	if (position > L->Length || position < 1) return NULL;
	else {	
		LPointer p = L->StartPoiner->next;
		int count = 1;
		while (p != NULL && count < position) {
			count++;
			p = p->next;
		}
		return p;
	}
}

int changeList(LinkListP L) { //    
	LPointer p = L->StartPoiner->next;
	p = p->next;
	if (!p) return -1;
	else {
		L->EndPointer = L->StartPoiner->next;
		while(p) {
			L->EndPointer->next = p->next;
			p->next = L->StartPoiner->next;
			L->StartPoiner->next = p;
			p = L->EndPointer->next;
		}
		return 1;
	}
}

void printLinkList(LinkListP L) { //  getNode       
	int i;
	for (i = 1; i <= L->Length; i++) {
		printf("the value of the %d position node is %d
", i, getNode(L, i)->x); } } void DelEvenPositionNode(LinkListP L) { // // // 2 3,4,5,6 int i; for (i = 2; i <= L->Length; i++) { DelNode(L, i); } } void DelEvenValueNode(LinkListP L) { // // , , int i = 1; while (i <= L->Length) { LPointer p = getNode(L, i); if (p && p->x % 2 == 0) { DelNode(L, i); } else if (p) { i++; } } } int main() { LinkListP L; int i; if (InitLinkList(L) == 1) { printf("Initization successfully
"); } else exit(1); for (i = 0; i < 10; i++) { // 0-9 LNode mLNode; mLNode.x = i; mLNode.next = NULL; if (InsertNode(L, mLNode) == -1) { printf("There are errors when insert node to linklist
"); } else { printf("Insert node successfully, the value of node is %d
", mLNode.x); } } //DelEvenPositionNode(L); printf("Have deleted all even position nodes
"); // 02468 DelEvenValueNode(L); printf("Have deleted all even value nodes
"); // 13579 changeList(L); printLinkList(L); return 0; }

좋은 웹페이지 즐겨찾기