每日算法(链表)

来源:互联网 发布:同盾大数据 编辑:程序博客网 时间:2024/05/16 11:46

1、一个有环链表,找出环路的开头结点。

LinkedListNode FindBeginning(LinkedListNode head){LinkedListNode slow = head;LinkedListNode fast = head;while(fast != null && fast.next !=null){slow = slow.next;fast = fast.next.next;if(slow == fast){break;}}if(fast ==null || fast.next ==null){return null;}slow = head;while(slow != fast){slow = slow.next;fast = fast.next;}return fast;}


 

2、检查链表是否为回文

boolean isPalindrome(LinkedListNode head){LinkedListNode slow = head;LinkedListNode fast = head;Stack<Integer> stack = new Stack<Integer>();while(fast !=null && fast.next !=null){stack.push(slow.data);slow = slow.next;fast = fast.next.next;}if(fast != null){slow = slow.next;}while(slow != null){int top = stack.pop().intValue();if(top != slow.data){return false;}slow = slow.next;}return true;}


 

0 0
原创粉丝点击