题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
反转链表的话,如果不考虑用栈,则需要一个辅助结点newHead,但是该节点不存储数据,把原链表结点按照前插法插入,这样链表就倒叙插入了,即完成了反转,最后返回辅助结点的next即可。 public class Solution { public ListNode ReverseList(ListNode head) { if(head==null){
return null;
}
ListNode cur=head; //指向待插入结点
ListNode reverseHead=new ListNode(0); //创建辅助结点
ListNode next=null; //保存待插入结点的下一个结点
while(cur!=null)
{
next=cur.next;
cur.next=reverseHead.next; //把辅助头结点的next赋值给插入结点的next属性
reverseHead.next=cur; //辅助头结点next指向插入结点
cur=next; //待插入结点变为下一个节点
}
head=reverseHead.next;
return head;
}
}
