206.反转链表
题目描述
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
题解
解法一
先设置一个数组,将链表元素依次存入数组;在将数组的元素倒序依次放回链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
int[] a = new int[5001];
ListNode p = head;
int i = 0;
while (p != null) {
a[i++] = p.val;
p = p.next;
}
// i--;
p = head;
while (p != null) {
i--;
p.val = a[i];
p=p.next;
}
return head;
}
}
解法二:双指针法
只需要改变链表的next指针的指向,直接将链表进行反转。
- 首先定义p指针,指向头结点;再定义一个pre指针,初始化为null
- 反转:将p指针的下一个节点用temp指针暂时保存一下,然后将p指针指向链表的前一个元素(p.next=pre)
- 接下来开始循环,pre=p;p=temp; p接着反转指向它的前一个元素pre,依次循环
- 直到p指针为空,返回pre即可
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode p=head;
ListNode pre=null;
ListNode temp=null;
while(p!=null){
temp=p.next;
p.next=pre;
pre=p;
p=temp;
}
return pre;
}
}