leetcode地址:https://leetcode-cn.com/problems/reverse-linked-list/comments/
要求:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
核心思想:遍历链表,使用两个变量来记录当前节点与下一节点,本来当前节点是指向下一节点的,但是反转,只需要把下一节点的next指针指向当前节点就好。
java实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null){
return head;
}
ListNode cur = head.next;
// 使输入的表头反转后指向null
head.next = null;
ListNode pre = head;
ListNode temp;
while (cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}