【编程】链表问题
来源:互联网 发布:钩尖江湖直销淘宝店 编辑:程序博客网 时间:2024/05/29 16:47
1。翻转单向链表
2。删除无序链表中值重复的节点
import java.util.HashSet;import java.util.Scanner;public class Node { public int value; public Node next; public Node(int data) { this.value = data; next = null; } public Node() { next = null; } //翻转链表 public static Node reverseList(Node head) { Node pre = null; Node next = null; while(head != null) { next = head.next; head.next = pre; pre = head; head = next; } return pre; } /** * 头插法创建链表,手动输入 */ public static Node createLinkedList() { Node head = null; Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { int reader = scanner.nextInt(); Node newNode = new Node(reader); newNode.next = head; head = newNode; } return head; } /* * 遍历元素 */ public static void travelLinkedList(Node head) { Node pnext = head; while(pnext != null) { System.out.print(pnext.value + " "); pnext = pnext.next; } System.out.println(); } /* * 删除无序链表中值重复的节点, 借助HashSet空间复杂度O(n),时间复杂度O(n) */ public static void removeRepeatElementMethodOne(Node head) { if(head == null) return; else { HashSet<Integer> set = new HashSet<Integer>(); Node pre = head; Node curr = head.next; set.add(head.value); while(curr != null) { if(set.contains(curr.value)) { pre.next = curr.next; } else { set.add(curr.value); pre = curr; } curr = curr.next; } } } /* * 除无序链表中值重复的节点,空间复杂度O(1)时间复杂度O(n^2) */ public static void removeRepeatElementMethodTwo(Node head) { Node cur = head; Node pre = null; Node next = null; while(cur != null) { pre = cur; next = cur.next; while(next != null) { if(cur.value == next.value) { pre.next = next.next; }else { pre = next; } next = next.next; } cur = cur.next; } } //测试翻转单向链表 public static void testReverseList() { Node head = createLinkedList(); //员链表顺序 travelLinkedList(head); Node newHead = reverseList(head); //翻转后链表顺序 travelLinkedList(newHead); } //测试删除无序链表中值重复的节点 public static void testRemoveRepeatElementOne() { Node head = createLinkedList(); removeRepeatElementMethodTwo(head); //removeRepeatElementMethodOne(head); travelLinkedList(head); } public static void main(String[] args) { //testReverseList(); testRemoveRepeatElementOne(); }}
阅读全文
0 0
- 【编程】链表问题
- 【编程】链表排序问题
- 编程之美----链表相交问题
- 编程之美----链表相交问题
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术--->6、关于链表的追赶问题
- 【July程序员编程艺术】之链表追赶问题
- 《程序员面试白皮书》关于链表的问题编程实践
- 程序员编程艺术:第九章、闲话链表追赶问题
- 编程问题
- 编程问题。。。。
- 编程问题
- VC++2012编程演练数据结构《2》单循环链表与约瑟夫问题
- bzoj2463谁能赢呢?
- Android圆角图片
- 浏览器内核
- C++返回值是二维数组
- 一个有用的查备件号的网站
- 【编程】链表问题
- easyui联动效果
- linux下的uname命令详解
- jupyter配置scala和Spark学习环境
- Java上传文件到服务器
- 根据经纬度计算两点之间的距离的公式推导过程以及google.maps的测距函数
- 线程-线程控制
- Caused by: java.lang.IllegalStateException
- 线程死锁