206 Reverse Linked List

来源:互联网 发布:php上传图片压缩大小 编辑:程序博客网 时间:2024/04/19 21:31

题目链接:https://leetcode.com/problems/reverse-linked-list/

题目:

Reverse a singly linked list.click to show more hints.Hint:A linked list can be reversed either iteratively or recursively. Could you implement both?

解题思路:
头插法

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseList(ListNode head) {        if(head == null || head.next == null)            return head;        ListNode p = head;        while(p.next != null) {            ListNode temp = p.next;            p.next = p.next.next;            temp.next = head;            head = temp;        }        return head;    }}
27 / 27 test cases passed.Status: AcceptedRuntime: 344 ms
0 0
原创粉丝点击