1.单向链表
#include<stdio.h> #include<stdlib.h> typedef struct Node{ int elem; struct Node *next; }Node,*List; List createList(); //创建空链表 void insertList(List list, int elem); //链表插入元素 void deleteList(List list, int elem); //链表删除元素 int lengthList(List list); //链表长度 void reverse(List list); //链表反转 void reverse2(List list); //链表反转 void traversal(List list); //链表遍历 Node *findKthTotail(List list,int k); //找到链表的倒数第k个元素
List createList(){ List list ; list = (Node *)malloc(sizeof(Node)); if(list == NULL) printf("内存不足,链表创建失败"); else { list->next=NULL; list->elem=0; return list; } return NULL; } void insertList(List list, int elem){ Node *insertnode; Node *firstNode; insertnode = (List)malloc(sizeof(Node)); if(insertnode == NULL) printf("内存不足,插入创建失败"); else { insertnode->elem = elem; firstNode = list->next; list->next = insertnode; if(firstNode == NULL) insertnode->next = NULL; else insertnode->next = firstNode; } } void deleteList(List list, int elem){ Node *t=list->next; Node *p=list; while(t!=NULL){ if(t->elem!=elem) { p=t; t=t->next; } else{ p->next=t->next; free(t); break; } } } int lengthList(List list){ int length=0; while(list->next != NULL){ length++; list=list->next; } return length; } void reverse(List list){ Node *t = list; Node *p = t->next; Node *q = p->next; if(p == NULL||q == NULL) return; else{ Node *temp; Node *temp1=p; while(q != NULL){ t->next = q; temp = q->next; q->next = p; p = q; q = temp; } temp1->next=NULL; } } void reverse2(List list){ Node *t = list; Node *p = t->next; Node *q; while(p->next != NULL){ q = p->next; p->next = t; t = p; p = q; } p->next=t; list->next->next = NULL; list->next = p; } void traversal(List list){ Node *t=list->next; while(t!=NULL){ printf("%d ",t->elem); t=t->next; } }
Node *findKthTotail(List list,int k){ //找到链表的倒数第k个元素
Node *pre;
Node *current = list;
int i;
for(i = 0;i < k-1 && current != NULL;i++){
current = current->next;
}
if(i==k-1)
{
pre =list;
while(current->next!=NULL){
current = current->next;
pre=pre->next;
}
return pre;
}else
return NULL;
}
void main(){ List list; int length; list = createList(); //带头结点链表 insertList(list,3); //添加元素 insertList(list,4); insertList(list,5); deleteList(list,5); //删除加元素 insertList(list,5); insertList(list,6); printf("反转前:"); traversal(list); reverse2(list); printf("反转后:"); traversal(list); length = lengthList(list); printf("list length is %d\n",length); }