1. 题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
2. 代码实现
非递归
/**
* 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 null;
ListNode pre = head, cur = head.next, p;
while(cur != null) {
p = cur.next;
cur.next = pre;
pre = cur;
cur = p;
}
head.next = null;
return pre;
}
}
递归
/**
* 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 || head.next == null) //链表为空 或 链表中只有一个元素
return head;
else{
ListNode newhead = reverseList(head.next);
head.next.next = head; //把head的后继结点变成head的前驱结点
head.next = null; //head是反转链表中最后一个结点
return newhead;
}
}
}