---
title: "Reverse Linked List"
author: "KickCode"
date: "2016-02-19T03:09:09Z"
tags: []
categories: ["编程语言"]
slug: "reverse-linked-list"
draft: false
lastmod: "2016-02-19T03:09:09Z"
id: 2277303
url: "https://kickcode.iteye.com/blog/2277303"
---

Reverse a singly linked list.

反转一个单向链表，采用头插法，设定两个指针pre和tem，tem记录head的下一个元素，从head开始依次指向它前面的元素，同时pre不断后移。代码如下：

```java

/**
 * 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) {
        ListNode pre = null;
        ListNode tem = null;
        while(head != null) {
            tem = head.next;
            head.next = pre;
            pre = head;
            head = tem;
        }
        return pre;
    }
}

```