题目描述
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
解题思路
-
这是一道链表的简单题,考察链表的反转;
-
我们考虑改变指针的指向,不需要新建链表;
-
借鉴卡哥的一幅图:
输入输出示例
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode tem = null;
ListNode cur = head;
while(cur != null){
tem = cur.next;
cur.next = pre;
pre = cur;
cur = tem;
}
return pre;
}
}