剑指offer系列(16):反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

样例

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路分析

双指针法,pre指针用于使原链表断链,指向反向,next指针用于节点的移动

代码及结果

public ListNode ReverseList(ListNode head) {
		if (head == null) {
			return null;
		}
		ListNode pre = null;
		ListNode next = null;
		while (head != null) {
			next = head.next;
			head.next = pre; //断链
			pre = head;
			head = next;
		}
		return pre;
    }

猜你喜欢

转载自blog.csdn.net/sun10081/article/details/82823382