单链表反转--java版

单链表反转–java版

思路

head—>a—->b—->c
变成:
head—>c—->b—->a

我们可以用循环的方式去实现,遍历一次链表即可。
1.用一个临时变量tmp存储 a的下一个元素b,a的next指向null,即”由头变尾”,head指向null。

head—->null
a b—->c
tmp—->b

2.因为此时tmp就是b,所以将tmp指向tmp的下一个元素c。将b next指向a

head—->null
a <—– b c
tmp—->c

3.因为此时tmp就是c,所以将tmp指向tmp的下一个元素null。将c next指向b

head—->null
a <—– b <—– c
tmp—->null

4.head——->c


/**
 * 链表反转
 * @author guohui
 *
 */
public class ReverLink {
    public static void main(String[] args) {

        Node<Integer> head = new Node<Integer>();
        Node<Integer> n1 = new Node<Integer>();
        Node<Integer> n2 = new Node<Integer>();
        Node<Integer> n3 = new Node<Integer>();
        head.next=n1;
        n1.data=1;
        n1.next=n2;
        n2.data = 2;
        n2.next = n3;
        n3.data = 3;

        reverse(head);
        Node<Integer> cur = head;
        while(cur!=null){
            System.out.println(cur.data);
            cur = cur.next;
        }
    }

    /**
     * 链表反转
     * @param head
     */
    public static void reverse(Node<Integer> head) {
        if(head ==null ){
            return ;
        }
        boolean isFisrt = true;
        Node<Integer> pre = head;
        Node<Integer> cur = head.next;
        Node<Integer> tmp;

        while(cur!=null){
            tmp = cur.next;
            if(!isFisrt){
            cur.next = pre;
            }else{
                isFisrt = false;
                cur.next = null;
            }
            pre = cur;
            cur = tmp;

        }

        head.next = pre;    
    }

}

/**
 * 链表数据结构
 * @author guohui
 *
 * @param <T>
 */
public class Node<T> {
    public Node next;
    public T data;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值