反转链表
题目:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
解答:
链表复制和赋值,过于基础:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode reverseList(ListNode head) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 ListNode node = new ListNode(head.val); 15 while(head.next != null){ 16 ListNode n = new ListNode(head.next.val); 17 n.next = node; 18 node = n; 19 head = head.next; 20 } 21 return node; 22 } 23 }