剑指offer面试题16 反转链表

解题思路:

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指针设为null
			head.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;
		
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值