题目描叙:
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入
复制
{1,2,3}
返回值
复制
{3,2,1}
solve1:非递归
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre=null; //初始化
while(head!=null){
ListNode next=head.next; //保存下一个要移动的节点
head.next=pre;//拼接
pre=head;//改变头节点
head=next;
}
return pre;
}
}
solve2:递归
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)return head;//空或者只有一个元素直接返回
ListNode returnNode=ReverseList(head.next);
head.next.next=head;
head.next=null;
return returnNode;
}
}
题目link:https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=190&&tqId=35203&rp=1&ru=/activity/oj&qru=/ta/job-code-high-rd/question-ranking