定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
思考题:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/class Solution {public ListNode reverseList(ListNode head) {ListNode dummy = null;while (head != null) {ListNode next = head.next;head.next = dummy;dummy = head;head = next;}return dummy;}}
递归
/*** 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;ListNode tail = reverseList(head.next);head.next.next = head;head.next = null;return tail;}}
