题目链接:. - 力扣(LeetCode)
思路一:由于题目并未要求结构与原结构相似,那么采用数学逻辑去做这道题就十分简单,依次将链表的元素取出放入集合中,然后反转集合,再创建新链表,依次将值放入即可。
/**
* 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) {
List<Integer> list=new ArrayList();
while(head!=null){
list.add(head.val);
head=head.next;
}
Collections.reverse(list);
ListNode cur=new ListNode(0);
ListNode tmp=cur;
for(int item:list){
ListNode node=new ListNode(item);
tmp.next=node;
tmp=tmp.next;
}
tmp=null;
return cur.next;
}
}
思路二:直接在原链表上进行操作,每一个节点都指向前一个节点,因此需要定义两个指针,一前一后,并且需要注意的是,操作结束后,最终返回的是前指针。
/**
* 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 cur=head;
ListNode pre=null;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}