单链表逆序--非递归算法

非递归的单链表逆序比较简单,只需要注意三个问题:
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);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值