Java实现单链表的反转

  • Post author:
  • Post category:java


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;

}

文章转自:

Java实现单链表的反转_Java-答学网

作者:

答学网

,转载请注明原文链接:http://www.dxzl8.com/



版权声明:本文为zl5186888原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。