代码中的注释详细,可直接运行,粘贴在编译器中研究更好!
创建结点 链表初始化 尾插法插入一个元素 头插法插入一个元素 按照下标插入一个元素 通过下标查询元素 通过下标更改元素 打印链表 通过下标删除元素 逆序输出链表 反转链表
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node,*List;
Node* CreateNode(int data);
List Init();
void InsertByTail(List L,int data);
void InsertByHead(List L,int data);
void InsertByIndex(List L,int data,int index);
void PrintList(List L);
void DeleteNodeByIndex(List L,int index);
int SelectByIndex(List L,int index);
void UpdateByIndex(List L,int data,int index);
int ListSize(List L);
Node* FindByIndex(List L,int index);
List ReversePrintList(List L);
List ReverseList(List L);
int main(){
List L = Init();
int i,index,num;
for(i=1;i<11;i++){
InsertByTail(L,i);
}
printf("原来的链表为:");
PrintList(L);
List new = ReverseList(L);
printf("逆转后为:");
PrintList(new);
return 0;
}
void InsertByTail(List L,int data){
Node *p, *node = CreateNode(data);
p = L;
node->data = data;
node->next = NULL;
while (p->next)
{
p = p -> next;
}
p->next = node;
}
Node* CreateNode(int data){
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
return node;
}
List Init(){
return CreateNode(0);
}
void PrintList(List L){
Node* p = L->next;
while (p != NULL){
printf("%d ",p->data);
p = p -> next;
}
printf("\n");
}
void InsertByHead(List L,int data){
Node *node = CreateNode(data);
node->next = L->next;
L->next = node;
}
void DeleteNodeByIndex(List L,int index){
Node *temp;
Node* p = FindByIndex(L,index);
if(index > ListSize(L) || index < 1){
return ;
}
temp = p->next;
p->next = p->next->next;
free(temp);
}
int ListSize(List L){
int i = 0;
Node* p = L->next;
while (p != NULL){
i++;
p = p-> next;
}
return i;
}
Node* FindByIndex(List L,int index){
int i;
Node* p = L;
for (i = 1; i < index; i++) {
p = p -> next;
}
return p;
}
void InsertByIndex(List L,int data,int index){
Node* p = FindByIndex(L,index);
Node* node = CreateNode(data);
node->next = p->next;
p->next = node;
}
int SelectByIndex(List L,int index){
Node* p = FindByIndex(L,index);
return p->next->data;
}
void UpdateByIndex(List L,int data,int index){
Node* p = FindByIndex(L,index);
p->next->data = data;
}
List ReversePrintList(List L){
if(L == NULL) return NULL;
ReversePrintList(L->next);
printf("%d ",L->data);
}
List ReverseList(List L){
List now = Init();
Node* p = L->next;
while (p!=NULL){
InsertByHead(now,p->data);
p = p->next;
}
return now;
}
|