反转链表

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

public class Solution {
    
    public ListNode ReverseList(ListNode head) {
        
        ListNode pre = head;
        ListNode in = null;
        ListNode post = null;
        if(pre == null)
            return null;
        if(pre.next == null)
            return pre;
        in = pre.next;
        pre.next = null;
        post = in.next;
        while(post != null) {
            
            in.next = pre;
            pre = in;
            in = post;
            post = in.next;
        }
        in.next = pre;
        return in;
    }
    public static void main(String[] args) {
        
        ListNode head = new ListNode(0);
        ListNode node = head;
        for(int i = 1; i <= 10; i++) {
            
            ListNode temp = new ListNode(i);
            node.next = temp;
            node = node.next;
        }
        node = head;
        while(node != null) {
            
            System.out.println(node.val);
            node = node.next;
        }
        Solution obj = new Solution();
        node = obj.ReverseList(head);
        while(node != null) {
            
            System.out.println(node.val);
            node = node.next;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容