【C/C++】单链表的倒置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/h84121599/article/details/85012983

(代码在末尾)

设有链表
head->1->2->3...
可用头插法将其倒置,具体步骤为:


1.创建指针p,t均指向head->next,p表示正在的节点,t表示待处理的节点
2.将head->next置为空,即NULL


3.若p指针为空,跳到步骤8,否则执行步骤4


4.令t指向下一个节点,即t=t->next


5.断开p节点,以头插法将其插入head后面


6.将p指针指向t


7.执行步骤3


8.结束函数

具体代码如下

void reverse(list* head)
{
  list *t,*p;
  t=p=head->next;//创建指针,对应步骤1
  head->next=NULL;//表头置空,对应步骤2
  while(p != NULL)//循环判断,对应步骤3
  {
    t=t->next;//t后移,对应步骤4
    p->next=head->next;//
    head->next=p;//头插法将p插入haed表,对应步骤5
    p=t;//处理下一个,对应步骤6    
  }  
  return;//结束函数,对应步骤8
}

猜你喜欢

转载自blog.csdn.net/h84121599/article/details/85012983