题目:
输入一个链表,反转链表后,输出新链表的表头
代码实现:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
//通过头插法
public ListNode ReverseList(ListNode head) {
//反转后的链表头结点
ListNode newHead=null;
ListNode pNode=head;
//保存当前结点
ListNode temp=null;
while(pNode!=null)
{
//保存当前结点
temp=pNode;
pNode=pNode.next;
//当前结点头插到新头结点前面
temp.next=newHead;
//头结点指向插入的结点
newHead=temp;
}
return newHead;
}
}