《剑指offer》——反转链表

来源:互联网 发布:网达软件 编辑:程序博客网 时间:2024/05/01 23:46

T:

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

constraints:

时间限制:1秒空间限制:32768K

考察的是对链表的操作。
跟排序差不多,依次讲节点插入头部,“头插法”。

这里写图片描述


code:

    /*    public class ListNode {        int val;        ListNode next = null;        ListNode(int val) {            this.val = val;        }    }*/    public class Solution {        public ListNode ReverseList(ListNode head) {            ListNode tempHead = new ListNode(0);            tempHead.next = head;            ListNode node = null;            // 空链表的情况            if (head == null) {                return head;            }            while (head.next != null) {                node = head.next;   // 将要插入前面的节点存储;                head.next = head.next.next; // 指针转换到其后继节点;                node.next = tempHead.next;  // 将该节点的指针指向第一个节点;                tempHead.next = node;   // 将虚的头结点的指针指向该节点。            }            return tempHead.next;        }    }
0 0