题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路
创建一个新的头节点,将原链表的所有结点通过头插法插入新的头节点之后。最终返回新的头节点的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 || head.next== null) {
return head;
}
ListNode newHead = new ListNode(0);
while (head != null) {
ListNode tmp = head;
head = head.next;
tmp.next = newHead.next;
newHead.next = tmp;
}
return newHead.next;
}
}
题目链接