非递归的单链表逆序比较简单,只需要注意三个问题:
1、保存从单链表上拆下的节点;
2、保存当前在链表上的节点,保证不断链;
3、判断循环结束条件。
初始状态:
prev = null;
head = head;
next = head.next;//保证不断链
开始逆序:
head.next = prev;//不会断链,next保持在链上(最后一个节点指向null)
prev = head;
head = next;
next = head.next;
循环进行如上四步操作。
终止条件:
head == null;
class ListNode{
int data;
ListNode next;
public ListNode(int x){
data = x;
next = null;
}
}
/**
* 单链表逆序
* 使用一个额外的Node空间
* */
public class Main {
public static void main(String[] args){
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
n1.next = n2;n2.next = n3; n3.next = n4;
ListNode(n1);
reverseList(n1);
ListNode(n4);
}
public static ListNode reverseList(ListNode head){
if(head == null || head.next == null){//逆序完成
return head;
}
ListNode pre = head;
ListNode cur = head.next;
while(cur != null){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
head.next = null;
return head;
}
//遍历单链表
public static void ListNode(ListNode nhead){
while(nhead.next != null){
System.out.println("当前节点:"+ nhead.data);
nhead = nhead.next;
}
System.out.println("当前节点:"+ nhead.data);
}
}