本文共 2224 字,大约阅读时间需要 7 分钟。
链表指定值清除
现在有一个单链表。链表中每个节点保存一个整数,再给定一个值val,把所有等于val的节点删掉。给定一个单链表的头结点head,同时给定一个值val,请返回清除后的链表的头结点,保证链表中有不等于该值的其它值。请保证其他元素的相对顺序。{1,2,3,4,3,2,1},2
{1,3,4,3,1}我的提交class ClearValue:
def clear(self, head, val):if not head: return None while head and head.val == val: head = head.next p = head h = None while p: if p.val == val: h.next = p.next else: h = p p = p.next #h.next = None return head
链表的回文结构
请编写一个函数,检查链表是否为回文。给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。#测试样例:{1,2,3,2,1}#返回:true{1,2,3,2,3}#返回:false我的提交class Palindrome:
def isPalindrome(self, pHead):stack = [] p = pHead while p: temp = p stack.append(temp) p = p.next p = pHead for _ in range((len(stack) // 2) + 1): temp = stack.pop() if p.val != temp.val: return False p = p.next return True
参考答案
import java.util.*;/*
public class ListNode { int val;ListNode next = null;ListNode(int val) { this.val = val;}
}*/
public class Palindrome { public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true;}ListNode n1 = head;ListNode n2 = head;while (n2.next != null && n2.next.next != null) { // find mid noden1 = n1.next; // n1 -> midn2 = n2.next.next; // n2 -> end}n2 = n1.next; // n2 -> right part first noden1.next = null; // mid.next -> nullListNode n3 = null;while (n2 != null) { // right part convertn3 = n2.next; // n3 -> save next noden2.next = n1; // next of right node convertn1 = n2; // n1 moven2 = n3; // n2 move}n3 = n1; // n3 -> save last noden2 = head;// n2 -> left first nodeboolean res = true;while (n1 != null && n2 != null) { // check palindromeif (n1.val != n2.val) { res = false;break;}n1 = n1.next; // left to midn2 = n2.next; // right to mid}n1 = n3.next;n3.next = null;while (n1 != null) { // recover listn2 = n1.next;n1.next = n3;n3 = n1;n1 = n2;}return res;}}转载于:https://blog.51cto.com/13545923/2054453