单链表的创建 反转 求中点 删除节点
struct Node{
int data;
struct Node* Next;
};
首先是看链表的节点 链表的结点包括两部分 一部分是数据域另一部分是指针域 数据域用来存放该节点的数据 指针域用来连接节点。
单链表有两种表示方法一种是有头结点的链表 另一种是无头结点的链表
什么是头结点呢,头结点与我们创建的节点类似,但头结点的数据域为空,为什么要引入头结点呢,因为有了头结点能方便我们的一些操作,但链表不是一定要有头结点。那我们下面就来创建一个头结点。
struct Node* headNode(){
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->Next = NULL;
return head;
}
创建了头结点接下来我们创建链表:
void creatlist(struct Node* head){
int n;
scanf("%d",&n);//请输入你要创建的节点个数
while(n){
int data;
scanf("%d",&data);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->Next = NULL;
head->Next = newNode;
head = newNode;
n--;
}
}
好 这就是有头结点链表的创建。下面我们再看看无头结点链表的创建:
struct Node* createNode(){
struct Node* head = NULL;
struct Node* p = NULL;
int data,n;
scanf("%d",&n);
int i;
for(i = 0;i < n;++i){
struct Node* q = (struct Node*)malloc(sizeof(struct Node));
scanf("%d",&data);
q->data = data;
q->Next = NULL;
if(head == NULL){
head = q;
p = q;
}
else{
p->Next = q;
p = q;
}
}
}
创建好了链表 接下来写一下链表的输出:
void printlist(struct Node* head){
while (head != NULL){
printf("%d",head->data);
head = head->Next;
}
}
有头结点的向后移一下。
下面写一下链表的删除:删除指定位置
void dellist(int n,struct Node* head){
struct Node* headfront = head;
struct Node* head1 = headfront->Next;
if(head == NULL){
printf("删除失败,链表为空");
}
else if(n==1){
free(headfront);
}
else{
int i;
for(i = 1;i < n;++i){
headfront = head1;
head1 = headfront->Next;
if(head1 == NULL && i != n-1){
printf("该链表没有该元素");
return;
}
}
headfront->Next = head1->Next;
free(head1);
}
}
好 下面在说一下求链表中点:(快慢指针法)
struct Node* midlist(struct Node* head){
struct Node* low = head;
struct Node* fast = head;
while(fast){
low = low->Next;
fast = fast->Next->Next;
}
return low;
}
最后再写一下链表的反转:
struct Node* turnlist(struct Node* head){
struct Node* newhead = NULL;
struct Node* perv = NULL;
while(head != NULL){
struct Node* t = head->Next;
if(t == NULL){
newhead = head;
}
head->Next = perv;
perv = head;
head = perv->Next;
}
return newhead;
}
struct Node* turnlist2(struct Node* head){
if(head == NULL || head->Next == NULL){
return head;
}
struct Node* q = head->Next;
struct Node* newhead = turnlist2(q);
p->Next = head;
head->Next = NULL;//考虑这里是否能少掉该句
return newhead;
}
这个是递归实现