反转单链表的方法有哪些

发布时间:2021-02-22 17:58:46 作者:戴恩恩
来源:亿速云 阅读:106

这篇文章主要为大家详细介绍了反转单链表的方法有哪些,文中示例代码介绍的非常详细,具有一定的参考价值,发现的小伙伴们可以参考一下:

1 ,两两对换 

2, 放入数组,倒置数组

3, 递归实现

代码如下:

#include<stdio.h>
#include<malloc.h>
typedef struct Node
{

 int data;
 struct Node *pnext;


} Node,*pnode;
pnode CreateNode()
{

 pnode phead=(pnode)malloc(sizeof(Node));
 if(phead==NULL)
 {
  printf("fail to allocate memory");
  return -1;
 }
 phead->pnext=NULL;
 int n;
 pnode ph=phead;
 for(int i=0; i<5; i++)
 {

  pnode p=(pnode)malloc(sizeof(Node));
  if(p==NULL)
  {
   printf("fail to allocate memory");
   return -1;
  }
  p->data=(i+2)*19;
  phead->pnext=p;
  p->pnext=NULL;
  phead=phead->pnext;


 }
 return ph;
}
int list(pnode head)
{
 int count=0;
 printf("遍历结果:\n");
 while(head->pnext!=NULL)
 {
  printf("%d\t",head->pnext->data);
  head=head->pnext;
  count++;
 }
 printf("链表长度为:%d\n",count);
 return count;
}
pnode reverse2(pnode head)//两两节点之间不断交换
{
 if(head == NULL || head->next == NULL)
 return head;
 pnode pre = NULL;
 pnode next = NULL;
 while(head != NULL){
  next = head->next;
  head->next = pre;
  pre = head;
  head = next;
}
 return pre;
}
void reverse1(pnode head,int count)//把链表的节点值放在数组中,倒置数组
{
 int a[5]= {0};

 for(int i=0; i<count,head->pnext!=NULL; i++)
 {
  a[i]=head->pnext->data;
  head=head->pnext;

 }
 for(int j=0,i=count-1; j<count; j++,i--)
  printf("%d\t",a[i]);

}

pnode reverse3(pnode pre,pnode cur,pnode t)//递归实现链表倒置
{

 cur -> pnext = pre;
 if(t == NULL)
  return cur; //返回无头节点的指针,遍历的时候注意
 reverse3(cur,t,t->pnext);

}

pnode new_reverse3(pnode head){ //新的递归转置

 if(head == NULL || head->next == NULL)
  return head;
 pnode new_node = new_reverse3(head->next);
 head->next->next = head;
 head->next = NULL;
 return new_node; //返回新链表头指针

}
int main()
{
 pnode p=CreateNode();
 pnode p3=CreateNode();
 int n=list(p);
 printf("1反转之后:\n");
 reverse1(p,n);
 printf("\n");
 printf("2反转之后:\n");
 pnode p1=reverse2(p);
 list(p1);
 p3 -> pnext = reverse3(NULL,p3 -> pnext,p3->pnext->pnext);
 printf("3反转之后:\n");
 list(p3);
 free(p);
 free(p1);
 free(p3);
 return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 高效代码之反转单链表
  2. 反转单链表——16

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

单链表

上一篇:使用JavaScript怎么编写一个旋转木马轮播图效果

下一篇:利用opencv怎么对图像颜色的空间进行转换

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》