【面试题16】反转链表
2017-06-12 10:31
197 查看
题目:
输入一个链表,反转链表后,输出链表的所有元素。
分析:
反转链表只需改变链接方向,改变方向时需要将原本指向后一个结点的链接方向指向前一个结点,因此需要记录下三个结点。
实现:(非递归)
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;
}
输入一个链表,反转链表后,输出链表的所有元素。
分析:
反转链表只需改变链接方向,改变方向时需要将原本指向后一个结点的链接方向指向前一个结点,因此需要记录下三个结点。
实现:(非递归)
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;
}
相关文章推荐
- 面试题16:反转链表
- 【剑指offer】面试题16:反转链表
- 剑指offer 面试题16 反转链表
- 面试题16反转链表
- 面试题16:反转链表
- 剑指offer面试题16-反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 剑指Offer系列-面试题16:反转链表
- 剑指offer面试题16——反转链表
- 剑指offer_面试题16_反转链表(两种方法)
- (未完成)《剑指offer》(面试题16):反转链表
- 剑指Offer之面试题16:反转链表
- 【剑指Offer学习】【面试题16 :反转链表】
- 剑指offer:面试题16 反转链表
- 面试题 16:反转链表
- 《剑指Offer》面试题16:反转链表
- 面试题16 反转链表
- 【剑指offer】面试题16、反转链表