赞
踩
Java实现单链表的反转
方法一:遍历反转
class Node{
//构造方法
public int date; //0
public Node next; //null
public Node(int date){<!-- -->
this.date=date;
this.next=null;
}
}
public class link{
public Node reverse1(){
Node cur = this.head;
Node prev = null;
Node newHead = null;
while(cur != null){
Node curNext = cur.next; //备份后面的
if(curNext == null){
newHead = cur;
}
cur.next = prev; //反转第一个节点,将head.next先置为空;
//下一次反转时将前驱的节点给后面,造成反转效果
prev = cur; //后移
cur = curNext; //后移
}
return newHead;
}
}
方法二:头插法反转
public Node reverse2(){
Node temp = null;
Node cur = this.head;
if(cur == null || cur.next == null){
return head;
}
while(cur != null){
Node next = cur.next; //备份后面的
cur.next = temp.next; //1
temp.next = cur; //2
cur = next;
}
return temp.next;
}
作者:答学网,转载请注明原文链接:http://www.dxzl8.com/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。