题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路
反转链表实际上就是让链表的指针反向,若新建一个链表来实现反转或造成内存空间的浪费。我们只需要在原链表中改变节点的next指向即可,设定一个当前节点指向nowhead,当前节点的前一个节点prehead(初始为null),和当前节点的后一个节点headnext。在满足当前节点nowhead不为空的情况下,依次让nowhead指向prehead,headnext实际上起一个中间交换变量的作用。
代码实现
/**
* 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 headpre = null;
ListNode nowhead = head;
while (nowhead != null){
ListNode headnext = nowhead.next;
nowhead.next = headpre;
headpre = nowhead;
nowhead = headnext;
}
return headpre;
}
}