题目:输入一个链表,反转链表后,输出链表的所有元素。
解析:首先把所有的节点都存到list,然后用集合框架工具Collections的翻转方法把该链表翻转,然后根据集合节点创建单链表返回
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
List<ListNode> list = new ArrayList<>();
while(head!=null){
list.add(head);
head=head.next;
}
Collections.reverse(list);//翻转链表
///例如翻转后的链表为:5 4 3 2 1
//需要根据list创建单链表
head=list.get(0);//头节点的值设定
for(int i=list.size()-1;i>=1;i--){
ListNode p = new ListNode(list.get(i).val);//利用头插法创建单链表
p.next=head.next;
head.next=p;
}
return head;
}
}
解析二:用两个“指针”,preNode指向head的前一个节点,nextNode指向head的下一个节点
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
ListNode preNode=null;
ListNode nextNode=null;
while (head!=null){
nextNode=head.next;
head.next=preNode;
preNode=head;
head=nextNode;
}
return preNode;
}
}