鏈表結(jié)構(gòu)
typedef struct node{ ??
?int data;? ??
struct node *next;
}Node;?
1.鏈表的創(chuàng)建
Node *createList() {? ?
? ? ? ?Node * head = (Node*)malloc(sizeof(Node));? ?
? ? ? ?head->next = NULL;? ?
? ? ? ? return head;
}
2.鏈表的插入(頭插法)
void insertList(Node *head, int insertData){?
? ? ? ? Node * cur = (Node*)malloc(sizeof(Node));? ?
? ? ? ?cur->data = insertData;? ?
? ? ? ?cur->next = head->next;? ?
? ? ? ? head->next = cur;
}
//尾插法
void Insert()
{? int data,i;
? struct Data *head,*r,*s;??
?head = ( struct Data * )malloc( sizeof (struct Data));??
?head->next = NULL;? ?
?? r=head;? ??
for (i=0; i<n;i++){
s = ( struct Data *)malloc(sizeof (struct Data));
s->num = data;
s->next = r->next;
r->next = s;
r=s;
}
}
3.鏈表的遍歷
void traverseList(Node * head){?
? ? ? ?head = head->next;??
? ? ? ? while(head)? ? {? ??
? ? ? ? ? ? ?printf("%d\n",head->data);? ??
? ? ? ? ? ? ? head= head->next;? ?
? ? ? ? ? }
? }
4.計算鏈表的長度
int lenList(Node *head){? ?
? ? ? ?int len = 0;? ?
? ? ? ?head = head->next;? ?
? ? ? ?while(head)? ? { ? ? ? ?
? ? ? ? ? ? ? len++;? ? ??
? ? ? ? ? ? ? head= head->next;?
? ? ? ? }??
? ? ? return len;?
}
5.鏈表的查找
Node *searchList(Node *head, int findData){ ?
? ? ? ? ?head = head->next;?
? ? ? ? ?while(head)? ? {? ? ??
? ? ? ? ?if(head->data == findData)? ? ??
? ? ? ? ? ? ? ? break;? ? ??
? ? ? ? ? ? ? ? head= head->next;??
? ? ? ? }? ??
? ? ? ?return head;
}
6.鏈表的刪除
void deleteNodeList(Node *head, Node *pfind){??
? ? ? ? ?while(head->next != pfind) head = head->next;??
? ? ? ? ?head->next = pfind->next;??
? ? ? ? ?free(find);
? ?}
7.鏈表排序
void sortPopList(Node *head, int len){? ?
? ? ? Node* sh = NULL ,*p = NULL,*q = NULL; ? ??
? ? ? Node * tmp;? ?
? ? ?for(int i = 0; ?i < len-1; i++){
? ? ? ? ? ? ?sh = head;
? ? ? ? ? ? ?p = sh->next;
? ? ? ? ? ? ?q = p->next;
? ? ?for(int j=0; j < len - 1 -i; j++)
? ? {
? ? ? ? ? ?if(p->data > q->data)
? ? ? ? ? {
? ? ? ? ? ? ? ? ?sh->next? = q;
? ? ? ? ? ? ? ? ? p->next = q->next; ??
? ? ? ? ? ? ? ? ? q->next = p;
? ? ? ? ? ? ? ? ? tmp = p;
? ? ? ? ? ? ? ? ? p = q;
? ? ? ? ? ? ? ? ? q = tmp;
? ? ? ? ? ? }
? ? ? ? ? ?sh = sh->next;
? ? ? ? ? ?p = p->next;
? ? ? ? ? ?q = q->next;
? ? ? }
? ?}
}