题目
输入一个链表,反转链表后,输出新链表的表头。
思路
链表反转这是一个经典的题,要做到链表反转,我们只需要将链表中的next指向位置更改就行,在可以创建新链表的情况下,只需对新链表采用头插法来插入数据
代码部分
/*
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;
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}