网站建设资讯

NEWS

网站建设资讯

反转单链表的方法有哪些-创新互联

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

成都创新互联公司专注于龙海企业网站建设,成都响应式网站建设,成都商城网站开发。龙海网站建设公司,为龙海等地区提供建站服务。全流程定制制作,专业设计,全程项目跟踪,成都创新互联公司专业和态度为您提供的服务

1 ,两两对换 

2, 放入数组,倒置数组

3, 递归实现

代码如下:

#include
#include
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; ipnext!=NULL; i++)
 {
  a[i]=head->pnext->data;
  head=head->pnext;

 }
 for(int j=0,i=count-1; j 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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联建站。

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、建站服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站题目:反转单链表的方法有哪些-创新互联
标题路径:http://cdweb.net/article/jesee.html