c說話完成單鏈表算法示例分享。本站提示廣大學習愛好者:(c說話完成單鏈表算法示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是c說話完成單鏈表算法示例分享正文
#include <stdio.h>
#include <stdlib.h>
typedef char DataType;
typedef struct Node{
DataType data;
struct Node * Next;
}ListNode,* LinkList;
void Judement(LinkList head){ //斷定分派內存
if (!head){
printf("Overflow.");
exit(-1);
}
}
LinkList CreatListF(void){ //頭插法創立Single Linked List
DataType ch;
LinkList head = (ListNode*)malloc(sizeof(ListNode));
Judement(head);
ListNode* s;
ch = getchar();
while (ch != '\n'){
s = (ListNode*)malloc(sizeof(ListNode));
Judement(s);
s->data = ch;
s->Next = head->Next;
head->Next = s;
ch = getchar();
}
return head;
}
LinkList CreatListS(void){ //尾插法創立Single Linked List
char ch;
ListNode* s;
LinkList head = (ListNode*)malloc(sizeof(ListNode));
Judement(head);
ch = getchar();
while (ch != '\n'){
s = (ListNode*)malloc(sizeof(ListNode));
Judement(s);
s->data = ch;
head->Next = s;
head = s;
ch = getchar();
}
head->Next = NULL;
return head;
}
int GetLength(LinkList head){ //獲得長度
int length = 0;
LinkList p = head->Next;
while (p){
length += 1;
p = p->Next;
}
return length;
}
ListNode* GetNodeById(LinkList head, int i){ //依序號查找元素
if (i<1 || i>GetLength(head)){
exit(1);
}
int j=1; //避免極端情形掃描逾界
LinkList p = head->Next;
while (p != NULL && j < i){
j += 1;
p = p->Next;
}
return p;
}
ListNode* GetNodeByValue(LinkList head, DataType e){ //依值查找元素
LinkList p = head->Next;
while (p != NULL&&p->data != e){
p = p->Next;
}
return p;
}
int InsertList(LinkList head, DataType e, int i){ //拔出e值在第i節點
if (i<1 || i>GetLength(head) + 1){
exit(1);
}
LinkList s = (ListNode*)malloc(sizeof(ListNode));
s->data = e;
LinkList q, p = head;
int j = 1;
while (j <= i){
q = p;
p = p->Next;
j += 1;
}
s->Next = q->Next;
q->Next = s;
return 0;
}
int DeleteListNodeById(LinkList head, int i){ //依序號刪除節點
int j = 1;
ListNode* p,* q;
if (i<1 || i>GetLength(head)){
exit(1);
}
p = head;
while (j < i){
p = p->Next;
j += 1;
}
q = p->Next;
p->Next = q->Next;
free(q);
return 0;
}
int DeleteListRepeatNode(ListNode* head){ //消除冗余數據
ListNode* p, *q, *s;
if (p == NULL){
exit(1);
}
p = head->Next; //首節點有數據
while (p->Next != NULL){
q = p;
while (q->Next != NULL){
if (q->Next->data == p->data){
s = q->Next;
q->Next = q->Next->Next;
free(s);
}
q = q->Next;
}
p = p->Next;
}
return 0;
}