首页 技术 正文
技术 2022年11月15日
0 收藏 615 点赞 3,743 浏览 1541 个字

继续关于linked list的算法题:

删除排序链表中的重复元素

给定一个排序链表,删除所有重复的元素使得每个元素只留下一个。

案例:

给定 1->1->2,返回 1->2

给定 1->1->2->3->3,返回 1->2->3

解题思路:

这道题很简单,只需要比较当前节点和下一个节点,相同,则当前节点的指针指向下一节点的下一节点,不相同,递归下一节点。还是要注意同样的问题,单向链表是只能向后不能向前的,所以,要保留首节点。

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
pre = head
while pre.next:
if pre.val == pre.next.val:
pre.next = pre.next.next
else:
pre = pre.next
return head

我们继续来看另外一道题目

交换相邻结点

给定一个链表,对每两个相邻的结点作交换并返回头节点。

例如:
给定 1->2->3->4,你应该返回 2->1->4->3

你的算法应该只使用额外的常数空间。不要修改列表中的值,只有节点本身可以​​更改。

解题思路:

这里思路很明确,每次循环两个变量,在循环中维护两个变量,temp1和temp2,分别代表每当前次循环的第一个节点和第二个节点,交换他们的位置,并把原来的pre指针指向调整位置后的第一个节点,第二个节点的指针指向后续指针。dump代表新列表的头元素,pre代表每次循环的前置指针元素。代码如下:

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dump = pre = ListNode(-1)
if not (head and head.next):
return head
while head and head.next:
temp1 = head
temp2 = head.next
temp1.next = temp2.next
temp2.next = temp1
pre.next = temp2
pre = temp1
head = temp1.next return dump.next

递归的实现代码如下:

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
""" if not (head and head.next):
return head
new_head = head.next
head.next = self.swapPairs(head.next.next)
new_head.next=head
return new_head

  coding交流群:226704167,郑州程序员群:59236263愿和各位一起进步!

微信公众号:数据结构与算法 —— 链表linked list(03)欢迎关注

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,084
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,559
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,408
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,181
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,818
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,901