1.## 牛客网反转链表JAVA 链表头插法的使用##
项目场景:
牛客网 反转链表题
问题描述:
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入
{1,2,3}
返回值
{3,2,1}
原因分析:
一个好的反转链表的方法
解决方案:
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode temp = head;
ListNode Next =null;
ListNode head1= new ListNode(0);
while(temp!=null){
Next = temp.next;
temp.next=head1.next;
head1.next=temp;
temp=Next;
}
return head1.next;
}
}
问题描述:
从头开始遍历,逐个加入到新的头节点中,使用头插法解决
解决方案:
**要设置两个ListNode ,一个temp从头节点开始,再定义一个Next为头节点的下一个节点(Next=temp.next),再将temp.next指向新节点的next,再将temp=Next,当temp==null的时候结束循环。
while (temp!=null){
next=temp.next;
temp.next=reverseHead.next;
reverseHead.next=temp;
temp=next;
}