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

一、全部逆序

  

定义两个变量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;
}

  

posted @ 2017-03-12 22:24  贾斯彼迭  阅读(567)  评论(0编辑  收藏  举报