倒置链表有两种方法,一种是新建一个链表,遍历原链表,将数据用前插方式插入新链表。另一种设置三个结构体指针,current,pnext,ptemp,第一个指针current指向中间指针pnext所指向节点的前一个节点,第三个指针ptemp指向中间指针所指向节点的下一个节点,将中间节点的next指针指向前一个节点,三个指针向后移,最后将current指针赋给head指针,(head=current).
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}LNode;
LNode *head=NULL;
void printLinklist(LNode *head)
{
LNode *p=head;
if (p==NULL) {
printf("this linklist is null");
}
printf("\n链表节点为:");
while (p!=NULL) {
printf("\n%d",p->data);
p=p->next;
}
}
LNode *createLinklist()
{
LNode *p,*current;
head=malloc(sizeof(LNode));
p=head;
printf("please enter the data of linklist node:");
scanf("%d",&p->data);
while (1) {
current=malloc(sizeof(LNode));
printf("please enter the data of linklist node:");
scanf("%d",¤t->data);
if (current->data==-1) { //数据类型要匹配
free(current);
break;
}else{
p->next=current;
p=p->next;
}
}
p->next=NULL;
return head;
}
LNode *insertLinklist(LNode *head,int elem,int position)
{
LNode *p,*current = NULL;
p=head;
current=malloc(sizeof(LNode));
int i=0;
while (head!=NULL&&(i<position-1)&&p->next!=NULL) {
p=p->next;
i++;
}
current->data=elem;
current->next=p->next;
p->next=current;
free(current);
return head;
}
void deleteElem(LNode *head,int elem)
{
LNode *p;
p=head;
if (p->data!=elem) {
while (head!=NULL&&p->next!=NULL) {
if (p->next->data!=elem) {
p=p->next;
}
else{
p->next=p->next->next;
}
}
}else{
head=head->next;
p->next=NULL;
}
printf("\n删除节点成功!\n");
}
LNode *reverseLinklist(LNode *head)
{
LNode *newHead = NULL,*p,*current;
newHead=malloc(sizeof(LNode));
p=head;
newHead->next=NULL;
while (p!=NULL) {
current=malloc(sizeof(LNode));
current->data=p->data;
current->next=newHead->next;
newHead->next=current;
p=p->next;
}
return newHead->next;
}
//void reverseLinklist2(LNode *head)
//--------------------------------------------------
LNode * reverseLinklist2(LNode *head)
{
LNode *pnext,*current,*ptemp;
current=head;
pnext=head->next;
head->next=NULL;
while (pnext!=NULL) {
ptemp=pnext->next;
pnext->next=current;
current=pnext;
pnext=ptemp;
}
head=current;
return head;
}
int main(int argc, const char * argv[])
{
printf("创建链表:\n");
LNode *linklist=createLinklist();
printLinklist(linklist);
printf("\n插入节点:\n");
LNode *linklist1=insertLinklist(linklist,8,3);
printLinklist(linklist1);
printf("\n删除节点:\n");
deleteElem(linklist1, 8);
printLinklist(linklist1);
printf("\n倒置链表第一种方法:\n");
LNode *linklist2=reverseLinklist(linklist1);
printLinklist(linklist2);
printf("\n倒置链表第二种方法:\n");
linklist2=reverseLinklist2(linklist2);
printLinklist(linklist2);
return 0;
}