Continue with the algorithm of linked list:
Delete duplicate elements in sorted list
Given a sort list, delete all duplicate elements so that only one is left for each element.
Case study:
Given 1 - > 1 - > 2, return to 1 - > 2
Given 1 - > 1 - > 2 - > 3 - > 3, return to 1 - > 2 - > 3
Solutions:
This problem is very simple. Only the current node and the next node need to be compared. If they are the same, the pointer of the current node points to the next node of the next node. If they are different, the next node will be recursive. We should also pay attention to the same problem. A unidirectional linked list can only be backward but not forward. Therefore, the first node should be reserved.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class 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
Let's move on to another topic
Given a linked list, every two adjacent nodes are exchanged and the head node is returned.
For example:
Given 1 - > 2 - > 3 - > 4, you should go back to 2 - > 1 - > 4 - > 3.
Your algorithm should use only the extra constant space. Do not modify the values in the list, only the node itself can change them.
Solutions:
The idea here is very clear. Two variables are cycled each time, and two variables, temp1 and temp2, are maintained in the loop. They represent the first node and the second node of the previous cycle respectively, exchange their positions, and point the original pre pointer to the first node after adjusting the position, and the pointer of the second node to the subsequent pointer. dump represents the header element of the new list, and pre represents the leading pointer element of each loop. The code is as follows:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class 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
The implementation code of recursion is as follows:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class 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 exchange group: 226704167, Zhengzhou programmer group: 59236263, willing to make progress with you!
The official account of WeChat:Welcome to your attention.