Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//每次循环next节点时 用next节点val创建新节点 更改节点指针
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode newHead = new ListNode(head.val);
ListNode sub = head.next;
while (sub != null) {
ListNode node = newHead;
//创建新的节点 val是next节点的val
ListNode node1 = new ListNode(sub.val);
//新节点的next指针 指向前一个节点
node1.next = node;
//新节点赋给newHead
newHead = node1;
sub = sub.next;
}
return newHead;
}
}
/**
* 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 pre = null;
ListNode cur = head;
ListNode next = head.next;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}