定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
解法一:自己想的,用数组存储每个节点,然后再依次next等于前一个
/**
* 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[] head2 = new ListNode[5000];;
int i = 0;
while (head != null)
{
head2[i] = head;
head = head.next;
i++;
}
if (i > 0)
{
head = head2[i-1];
for (int j = i;j > 0;j--)
{
if (j == 1)
{
head2[0].next=null;
}
else
head2[j-1].next = head2[j-2];
}
}
return head;
}
}
解法二:评论区大佬的,迭代法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head, next = null;
while(cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}