反转链表

这里写图片描述
最后我的解决方案还是栈:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.Stack;
public class Solution {
    public ListNode ReverseList(ListNode head) {
		//利用栈
		if(head == null)
		{
			return null;
		}
		Stack stack = new Stack();
		ListNode p = head;
		while(p.next != null)
		{
			stack.add(p.val);
			p = p.next;
		}
		stack.add(p.val);//最后一个节点的值
		ListNode head2 = new ListNode((Integer)(stack.pop()));
		ListNode p2 = head2;
		while(!stack.isEmpty())
		{
			p2.next = new ListNode((Integer)(stack.pop()));
			p2 = p2.next;
		}
		return head2;
    }
}

但是考察的肯定不是希望怎么来,应该用指针,动态规划去解决。

	public static void main(String[] args) {
        ListNode listNode = ListNodeUtils.buildListNode(1, 2, 3);
        ReverseLink reverseLink = new ReverseLink();
        ListNode listNode1 = reverseLink.reverseList(listNode);
        AssertUtils.assertListNode(listNode1, 3, 2, 1);

        ListNode listNode2 = ListNodeUtils.buildListNode(1, 2, 3, 4, 5);

        ListNode listNode3 = reverseLink.reverseList2(listNode2);
        AssertUtils.assertListNode(listNode3, 5, 4, 3, 2, 1);
    }


    /**
     * 用两个指针,一个指向前一个,一个指向后一个
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 迭代
        ListNode p1 = null;
        ListNode p2 = head;
        while (p2 != null) {
            ListNode nextNode = p2.next;
            ListNode curNode = p2;
            p2.next = p1;
            p1 = curNode;
            p2 = nextNode;
        }
        return p1;
    }

    /**
     * 递归
     * 思路同理
     * @param head
     * @return
     */
    public ListNode reverseList2(ListNode head) {
        ListNode p1 = null;
        ListNode p2 = head;
        return recursion(p1 ,p2);
    }

    private ListNode recursion(ListNode p1, ListNode p2) {
        if (p2 == null) {
            return p1;
        }
        ListNode next = p2.next;
        p2.next = p1;
        p1 = p2;
        p2 = next;
        return recursion(p1, p2);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值