《剑指Offer》15反转链表
题目:
输入一个链表,反转链表后,输出新链表的表头。
过去提交通过的程序:
class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Solution { public ListNode ReverseList(ListNode pHead) { ListNode pHeadNode=null; ListNode pNode=pHead; ListNode pNext=null; ListNode pRev=null; while(pNode!=null) { pNext=pNode.next; if(pNext==null) { pHeadNode=pNode; } pNode.next=pRev; pRev=pNode; pNode=pNext; } return pHeadNode; } }
再写一次:(一次通过!!)
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { ListNode pHead=null; ListNode pNode=head; ListNode pNext=null; ListNode pRev=null; while(pNode!=null) { pNext=pNode.next; if (pNext==null) { pHead=pNode; } pNode.next=pRev; pRev=pNode; pNode=pNext; } return pHead; } }