这时强哥暑假上课时讲的,几个月后又看了一下,决定加点注释。
这个链表的封装程度是比较高的。基本不用用户自己写东西,直接用就好。
其次,这个链表的函数都是把链表的地址扔进去直接修改链表,而不是扔个原链表,改完后在把新的扔出来。
#include <stdio.h>
#include <stdlib.h>
int N = 20;
struct Node{
int data;
struct Node* next;
};
int searchfor(int *a, int len, int x){
if(len<1) return -1;
if(*a == x) return N-len;
return searchfor(a+1,len-1,x);
}
/*int main(){
int array[20] = {1,3,5,7,9,2,4,6,8,0,11,12,13,14,15,18};
int flag = 0;
flag = searchfor(array,N,22);
printf("%d\n",flag);
return 0;
}*/
void createList(struct Node** phead){
*phead = NULL;
}
struct Node* createNode(int item){
struct Node *tmp;
tmp = (struct Node*)malloc(sizeof(struct Node));
if(!tmp) return NULL;
tmp->data = item;
tmp->next = NULL;
return tmp;
}
int insertAtHead(struct Node** phead, int it){
struct Node* tmp;
tmp = createNode(it);
if(!tmp) return 0;
tmp->next = *phead;
*phead = tmp;
return 1;
}
void printList(struct Node* head){
while(head){
printf("%d ",head->data);
head = head->next;
}
putchar('\n');
}
int delHead(struct Node **phead){
if(*phead == NULL) return 0;
struct Node* tmp;
tmp = *phead;
*phead = (*phead)->next;
free(tmp);
return 1;
}
int deleteAt(struct Node **phead,int index){
if(index<1) return 0;
if(index==1) delHead(phead);
else{
int count=1;
struct Node *tmp=*phead;
while(tmp&&count<index-1){
tmp=tmp->next;
count++;
}
if(!tmp) return 0;
struct Node *newtmp;
newtmp=(*tmp).next;
(*tmp).next=(*(tmp->next)).next;
free(newtmp);
}
}
struct Node* findByValue(struct Node*head, int item){
while(head){
if(head->data == item) return head;
head = head->next;
}
return NULL;
}
struct Node* findByIndex(struct Node*head, int index){
if(index < 1) return NULL;
int count = 1;
while(head && count<index){
count++;
head = head->next;
}
return head;
}
int insertAt(struct Node**phead, int item, int index){
if(index < 1) return 0;
if(index == 1)
return insertAtHead(phead, item);
int count = 1;
struct Node* tmp = *phead;
while(tmp && count<index-1){
tmp = tmp->next;
count++;
}
if(!tmp) return 0;
struct Node* newnode;
newnode = createNode(item);
if(!newnode) return 0;
newnode->next = tmp->next;
tmp->next = newnode;
return 1;
}
int main(){
struct Node* head;
createList(&head);
insertAtHead(&head,20);
insertAtHead(&head,30);
insertAtHead(&head,40);
printList(head);
insertAt(&head, 15, 2);
printList(head);
deleteAt(&head,2);
printList(head);
return 0;
}