题目描述
(题目来自牛客网)
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围: 0\leq n\leq10000≤n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
个人答案:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
if(head.val==0){
return null;
}
if(head.next==null){
return head;
}
ListNode temp=new ListNode(-1);
ListNode lastNode;
do{
if(temp.val!=-1){
lastNode= temp;
}else{
lastNode=new ListNode(head.val);
}
head=head.next;//切换到下一点
temp=new ListNode(head.val);//当前点
temp.next=lastNode;
}
while(head.next!=null);
return temp;
}
}
示例答案
论坛上看到的高赞回答
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}
解析:
假设入参{1,2,3}
各变量每次while情况如下:
序号 | pre | next | head |
---|---|---|---|
-1 | null | null | {1,2,3,null} |
0 | {1,null} | {2,3.null} | {1,null}->{2.3.null} |
1 | {2,1,null} | {3.null} | {2,1,null}->{3,null} |
2 | {3,2,1,null} | {null} | {null} |