问题描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解答思路:
思路1:先用集合收集所有节点的元素,然后反转,再重新赋值给所有节点;效率不高,但是适合小白理解,也提供一种不一样的解题思路。
题后感:思路要清楚,选择正确的方法;另外,涉及到链表的题,画图很重要,助于理解
java版答案(只含函数):
//个人答案
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.util.ArrayList;
class Solution {
public ListNode reverseList(ListNode head) {
ArrayList<Integer> list = new ArrayList<>();
ListNode thisNode=null;
thisNode = head;
while (thisNode != null) {
list.add(thisNode.val);
thisNode = thisNode.next;
}
Object[] arr = list.toArray();
thisNode = head;
for(int i=list.size()-1;i>=0;i--){
head.val=(int) arr[i];
head = head.next;
}
return thisNode;
}
}
//优秀标准答案1
class Solution {
public ListNode reverseList(ListNode head) {
ListNode newNode = head,oldNode = null;
while(newNode != null){
ListNode next = newNode.next;
newNode.next = oldNode;
oldNode = newNode;
newNode = next;
}
return oldNode;
}
}
//优秀标准答案2
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;//先将下一节点保存起来,假设这里的head指代当前节点
head.next = pre;//当前节点指向前一节点(完成反转)
pre = head;//前一节点后移,变成当前节点
head = next;//当前节点后移,变成下一个节点,又从下一个节点开始
}
return pre;
}
上面不容易理解?自己需要动手画图。
想通过简单的图解法来理解?可以参考这篇博客
https://blog.csdn.net/xyh269/article/details/70238501