反转链表

2018-06-03  本文已影响0人  twilight_mao

题目描述

输入一个链表,反转链表后,输出链表的所有元素。

思路

1.定义3个指针,before=null/node=head/after=null,保存3个状态

代码

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode node=head;
        ListNode before=null;
        ListNode after=null;
        while(node!=null){
           after=node.next;
           node.next=before;
           before=node;
           node=after;
        }
        return before;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读