题目描述
输入一个链表,反转链表后,输出链表的所有元素。
方法1:将单链表储存为数组,然后按照数组的索引逆序进行反转。
方法2:使用三个指针遍历单链表,逐个链接点进行反转。
方法3:从第2个节点到第N个节点,依次逐节点插入到第1个节点(head节点)之后,最后将第一个节点挪到新表的表尾。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pReversedHead=head;
ListNode pNode=head;
ListNode pPrev=null;
while(pNode!=null){
ListNode pNext=pNode.next;
if(pNext==null){
pReversedHead=pNode;
}
pNode.next=pPrev;
pPrev=pNode;
pNode=pNext;
}
head=pReversedHead;
return head;
}
}