LinkedList——No.237:Delete node in a linkedlist

Problem:

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Explanation:

给定一个链表,交换相邻的两个结点,两个两个交换,但是不能通过改变结点的值。

My Thinking:

正向遍历链表,设置pre,cur,next三个指针,通过改变三个指针之间的指向关系对cur和next进行交换,时间复杂度O(n)。

My Solution:

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode pre=new ListNode(-1);
        pre.next=head;
        ListNode cur=head;
        ListNode next;
        if(head==null)
            next=null;
        else
            next=head.next;
        while(next!=null){
//结点交换
            pre.next=next;
            if(cur==head)
                head=next;
            cur.next=next.next;
            next.next=cur;
            //指针后移
            pre=cur;
            if(pre.next!=null)
                next=pre.next.next;
            else
                next=null;
            cur=pre.next;
        }
        return head;
    }
}

Optimum Thinking:

  1. 使用递归,从后向前两个两个比较,返回交换后的前一个元素,时间复杂度为O()
  2. 和My Thinking一样

Optimum Solution:

(1)

我写的:

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null)
            return head;
        ListNode next=swapPairs(head.next.next);//两个两个递归,返回交换后的前一个结点
        ListNode newhead=head.next;//设置一个新头(两个结点交换后的第一个元素,也就是交换前的第二个元素head.next)
        head.next.next=head;
        head.next=next;
        return newhead;
    }
}

讨论中写的:

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if ((head == null)||(head.next == null))
            return head;
        ListNode n = head.next;
        head.next = swapPairs(head.next.next);
        n.next = head;
        return n;
    }
}

讨论中写的答案更简洁一点,思路完全一样。

(2)同My Solution。

庆祝一下第一次自己把递归写出来!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值