数据结构——两个有序链表序列的合并(Swift)
在学习的时候作业只能用c语言,写完提交后用swift重新写一遍,实现结构不太相同。
import Foundation
class ListNode{
var data: Int
var next: ListNode?
init(_ data: Int) {
self.data = data
self.next = nil
}
}
class List {
var head: ListNode?
var tail: ListNode?
func appendToTail(_ data: Int){
if tail == nil {
tail = ListNode(data)
head = tail
}else{
tail!.next = ListNode(data)
tail = tail!.next
}
}
func AppendTail(Node: ListNode){
if tail == nil{
tail = Node
head = tail
}else{
tail!.next = Node
tail = tail!.next
}
}
func appendToHead(_ data: Int){
if head == nil{
head = ListNode(data)
tail = head
}else{
let temp = ListNode(data)
temp.next = head
head = temp
}
}
func printList(){
if head == nil{
print("NULL")
}else{
var temp = head
while(temp != nil){
print(temp!.data,terminator: " ")
temp = temp!.next;
}
}
}
func merge(withList L2: List) -> List{
var L = List.init()
var Node1 = head
var Node2 = L2.head
var t1: Int
var t2: Int
while (Node1 != nil && Node2 != nil){
t1 = Node1!.data
t2 = Node2!.data
if t1 <= t2{
L.AppendTail(Node: Node1!)
Node1 = Node1!.next
}else{
L.AppendTail(Node: Node2!)
Node2 = Node2!.next
}
}
Node1 != nil ? (L.AppendTail(Node: Node1!)) : (L.AppendTail(Node: Node2!))
return L
}
init() {
head = nil
tail = nil
}
}
func Read() ->List {
let L = List.init()
let r1 = Int(readLine()!)!
if r1 != 0 {
let intput = readLine()!.components(separatedBy: NSMutableCharacterSet.whitespaces)
let datas = intput.map {Int($0)!}
for i in 0...(r1-1){
L.appendToTail(datas[i])
}
}else{
exit(0)
}
return L
}
let L = Read()
let L2 = Read()
let L3 = L.merge(withList: L2)
L3.printList()
以上。

浙公网安备 33010602011771号