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

来源:互联网 发布:php相似图片搜索 api 编辑:程序博客网 时间:2024/05/29 05:06
/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*///1.再进行逆序输出的时候需要先保存在head的下一节点,避免链表因为失去头结点而发生错误   next = head.next;//2.此时便可以开始进行逆序   将最后一个节点指向向前节点   head.next = pre;//3.然后将向前节点后移指向头结点   pre = head;//4.然后将头结点指向像一个节点从而实现了逆序   head = next;public class Solution {    public ListNode ReverseList(ListNode head) {        if(head == null){            return null;        }        ListNode pre = null;        ListNode next = null;        while(head != null){            //经典逆序的输出里面的链表元素            next = head.next;            head.next = pre;            pre = head;            head = next;        }        return pre;    }}
阅读全文
0 0
原创粉丝点击