题目:
输入一个链表,反转链表后,输出链表的所有元素。
分析:
反转链表只需改变链接方向,改变方向时需要将原本指向后一个结点的链接方向指向前一个结点,因此需要记录下三个结点。
实现:(非递归)
public ListNode ReverseList(ListNode head) {
ListNode cur = head;
ListNode next = null;
ListNode pre = null;
if (head == null || head.next == null) {
return head;
}
while (cur != null) {
next = cur.next;
// 改变链方向
cur.next = pre;
// 移动结点,继续操作
pre = cur;
cur = next;
}
return pre;
}
实现:递归:
public ListNode Reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode secondElem = head.next;
head.next = null;
ListNode reverseRest = Reverse(secondElem);
secondElem.next = head;
return reverseRest;
}