算法-----单链表逆序

Posted 贾斯彼迭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法-----单链表逆序相关的知识,希望对你有一定的参考价值。

一、全部逆序

  

定义两个变量pre, next,与节点head一起,遍历整个链表。

while(head != null){
  next = head.next;
  head.next = pre;
  pre = head;
  head = next;  
}

  二、 部分逆序

首先找到需要逆序的节点区域的前一个节点和后一个节点。记为 pre,pos。

定义3个变量cur, next1, next2. 遍历链表。

Node cur = pre.next;
Node next1 = cur.next;
cur.next = pos;
Node next2 = null;

while(next1 != pos){
   next2 = next1.next;
   next1.next = cur;
   cur = next1;
   next1 = next2;
}

  

以上是关于算法-----单链表逆序的主要内容,如果未能解决你的问题,请参考以下文章