反转链表
题目
输入一个链表,反转链表后,输出链表的所有元素。
思路
画图。
代码
//非递归
public ListNode ReverseList(ListNode head){
if (head==null||head.next==null){
return head;
}
ListNode next = null;
ListNode pre = null;
while (head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
//递归
public ListNode ReverseList_II(ListNode head) {
if (head==null||head.next==null){
return head;
}
ListNode reverseNode = ReverseList(head.next);
head.next.next=head;
head.next=null;
return reverseNode;
}