时间久了,怕忘了,就写下来,算是一个回忆吧,这是常见的数据结构:
#include<stdio.h>
typedef struct ListNode
{
int key;
struct ListNode *next;
}ListNode;
ListNode *insertList(ListNode *head,int value); //创建一个单链表和向一个链表中插入元素,这里默认的是头插入法
int ListLength(ListNode *head); //计算单链表的长度,不算head节点
ListNode *deleteList(ListNode *head,int location); //删除单链表中某一位置的节点,第一个节点(不是head节点)位置为1,
ListNode *insertList(ListNode *head,int value)
{
if(head->next==NULL)
{
ListNode *node=(ListNode *)malloc(sizeof(ListNode));
node->key=value;
node->next=head->next;
head->next=node;
node->next=NULL;
return head;
}
ListNode *node=(ListNode *)malloc(sizeof(ListNode));
node->next=head->next;
head->next=node;
node->key=value;
return head;
}
int ListLength(ListNode *head)
{
if(head->next==NULL)return 0;
ListNode *node=head;
int count=0;
while(node->next!=NULL)
{
count++;
node=node->next;
}
return count;
}
ListNode *deleteList(ListNode *head,int location)
{
int length=ListLength(head);
if(location>length || location<=0)
return head;
ListNode *previous=head;
ListNode *node=head->next;
int i=1;
while(i<location)
{
previous=previous->next;
node=node->next;
i++;
}
previous->next=node->next;
return head;
}
void printReverse(ListNode *head)
{
if(head==NULL)
return;
printReverse(head->next);
printf("%d\t",head->key);
}
int main()
{
printf("请输入你要输入的数据元素的个数:\n");
int length;
scanf("%d",&length);
int a[length],i;
ListNode *head=NULL;
head=(ListNode *)malloc(sizeof(ListNode));
head->next=NULL;
printf("请分别输入每个元素:\n");
for(i=0;i<length;++i)
{
scanf("%d",&a[i]);
head=insertList(head,a[i]);
}
printf("此单链表长度为:%d\n",ListLength(head));
printf("正序输出链表:\n");
ListNode *node=head->next;
while(node!=NULL)
{
printf("%d\t",node->key);
node=node->next;
}
printf("\n反序输出链表:\n");
printReverse(head->next);
printf("\n请输入要删除的位置:\n");
int location;
scanf("%d",&location);
head=deleteList(head,location);
printf("输出删除指定位置后的单链表:\n");
node=head->next;
while(node!=NULL)
{
printf("%d\t",node->key);
node=node->next;
}
return 0;
}