Swift 实现链表反转

16 篇文章 0 订阅

//示例:

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

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

//进阶:

//你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

class ListNode {
    var val: Int
    var next: ListNode?
    init(_ val: Int) {
         self.val = val
         self.next = nil
     }
 }


class Solution {
    var head: ListNode? = nil
    var current: ListNode? = nil
    
    func appendElement(_ data: Int) {
        if head == nil {
            head = ListNode(data)
            current = head
        } else {
            current?.next = ListNode(data)
            current = current?.next
        }
    }
    
    //初始化
    func initNode() -> ListNode{
        for index in 1...5 {
            self.appendElement(index)
        }
        return head ?? ListNode(0)
    }
    
    //求链表长度
    func getLenght(_ head: ListNode?) -> Int {
        if head == nil {
            return -1
        }
        var lenght = 0
        current = head
        while current != nil {
            lenght += 1
            current = current?.next
        }
        return lenght
    }
    //迭代法实现链表反转
    func reverseList(_ head: ListNode?) -> ListNode? {
        var cur: ListNode? = nil
        var pre: ListNode? = head
        while pre != nil {
            let temp = pre?.next
            pre?.next = cur
            cur = pre
            pre = temp
        }
        return cur
    }
    //递归法实现链表反转
    func reverseList2(_ head: ListNode?) -> ListNode? {
        if head == nil || head?.next == nil {
            return head
        }
        let newNode = reverseList2(head?.next)
        head?.next?.next = head
        head?.next = nil
        return newNode
    }
    //打印链表
    func println(_ node: ListNode?) {
        guard let node = node else {
            return
        }
        current = node
        while current != nil {
            print("\(current?.val ?? 0)")
            current = current?.next
        }
    }
    
}

 

//应用调用
let solution = Solution()
let node =  solution.initNode()
print("--------反转前-------")
solution.println(node)
let newNode1 = solution.reverseList(node)
print("--------反转后-------")
solution.println(newNode1)
let newNode = solution.reverseList2(newNode1)
print("--------再次反转后-------")
solution.println(newNode)
print("链表长度:", solution.getLenght(newNode))

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值