剑指offer面试题16 反转链表

来源:互联网 发布:如何在淘宝卖高仿鞋 编辑:程序博客网 时间:2024/06/05 04:14

解题思路:

1.非递归:设置两个指针,一个指针p指向当前节点,一个指针after指向当前节点的下一个节点,从头结点开始遍历链表,交换指针的位置,在交换之前,需要保存下一次after节点的位置,因此需要一个临时变量来存储。最后将原来头部的指针的next设为null。

2.递归:递归的终止条件是当到达原来元链表的尾部时,返回尾指针,也就是新链表的头结点,将head的后一个指针的next域置为head,实现反转操作,并将head的next域置为null。

/** *反转链表 */public class Solution {public ListNode ReverseList(ListNode head) {if(head == null) {return null;}ListNode p = head;ListNode after = head.next;if (after == null) {//证明此时单链表中只有一个节点return head;} else {while (after != null) {//保存after的后一个节点ListNode temp = after.next;//进行指针的交换after.next = p;//p后移,after后移p = after;after = temp;}//最后将尾部的next指针设为nullhead.next = null;return p;}    }//递归地实现反转链表public ListNode ReverseList_recursive(ListNode head) {if (head == null || head.next == null) {return head;}ListNode newHead = ReverseList_recursive(head.next);head.next.next = head;head.next = null;return newHead;}}


原创粉丝点击