【剑指offer】面试题24-反转链表

题目

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

1.思路

思路1
遍历链表,将链表的结点逐个摘下,用尾插法拼接到新的空链表尾部。
思路2
遍历两次链表:
第一次遍历链表,找到链表的最后一个结点lastnode
第二次遍历链表,把链表的结点逐个用头插法拼接到lastnode之后。

2.代码(Java实现)

解题代码在第三部分,三部分组成完整的代码。
public class Main {
	public static void main(String[] args) {
		ListNode head = new ListNode(0);
		ListNode tail = head;
		// 尾插法创建一个简单的链表
		for (int i = 1; i < 5; i++) {
			ListNode p = new ListNode(i);
			tail.next = p;
			tail = tail.next;
		}
		ListNode check = head;
		while(check != null) {
			System.out.print(check.val + " ");
			check = check.next;
		}
		Solution solution = new Solution();		
		// 输出检查链表是否逆置
		ListNode checks = solution.ReverseList(head);
		while(checks != null) {
			System.out.print(checks.val + " ");
			checks = checks.next;
		}
		
	}
}
class ListNode{
	// 链表结点数据结构
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
}
// 方法 1:借助新的空链表,尾插法逆置
class Solution {
	public ListNode ReverseList(ListNode head) {
		// 创建空链表  
		ListNode old = head;
		ListNode temp = null;
		ListNode flag = null;
		// 尾插法创建链表
		while(old != null) {
			temp = old;
			old = old.next;
			temp.next = flag;
			flag = temp;
		}
		return flag;*/
		if (head == null) {
			return null;
		}
		ListNode result = head;
		while(result.next != null) {
			result = result.next;
		}
		
		ListNode index = head;
		ListNode item = null;
		// 头插法创建链表
		while(index != result) {
			item = index;
			index = index.next;
			item.next = result.next;
			result.next = item;
		}
		return result;
    }
}
// 方法 2:头插法,只靠原链表完成逆置
class Solution {
	public ListNode ReverseList(ListNode head) {
		if (head == null) {	// 判断链表是否为空
			return null;
		}
		ListNode result = head;
		// 遍历找到链表的最后一个结点
		while(result.next != null) {
			result = result.next;
		}
		ListNode index = head;
		ListNode item = null;
		// 头插法逆置链表
		while(index != result) {
			item = index;
			index = index.next;
			item.next = result.next;
			result.next = item;
		}
		return result;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值