LeetCode 206. Reverse Linked List

孤街醉人 提交于 2020-01-20 01:31:17

Description

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution

就新建一个头结点,然后遍历原链表,使用头插法搬到新链表中。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode p = head;
        ListNode newHead = new ListNode(0);
        newHead.next = null;
        while(p != null){
            ListNode q = p;
            p = p.next;
            q.next = newHead.next;
            newHead.next = q;
        }
        return newHead.next;
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!