[关闭]
@XQF 2018-03-07T22:49:24.000000Z 字数 1334 阅读 729

单链表的操作(删除和排序)

数据结构与算法


  1. class ListNode {
  2. int val;
  3. ListNode next;
  4. public ListNode(int val) {
  5. this.val = val;
  6. }
  7. }
  8. class MyLinkedList {
  9. private ListNode head;
  10. public void add(ListNode node) {
  11. if (length() == 0) {
  12. head = node;
  13. } else {
  14. ListNode p = head;
  15. while (p.next != null) {
  16. p = p.next;
  17. }
  18. p.next = node;
  19. }
  20. }
  21. // 删除
  22. public boolean delete(int index) {
  23. ListNode p = head;
  24. if (length() == 0 || length() < index + 1) {
  25. return false;
  26. }
  27. int counter = 0;
  28. if (index == 0) {
  29. head = p.next;
  30. }
  31. //这里一定要熟练,主要是找前一个
  32. while (p.next != null) {
  33. if (counter == index - 1) {
  34. if (p.next.next != null) {
  35. p.next = p.next.next;
  36. } else {
  37. p.next = null;
  38. }
  39. break;
  40. } else {
  41. p = p.next;
  42. counter++;
  43. }
  44. }
  45. return true;
  46. }
  47. public int length() {
  48. int counter = 0;
  49. ListNode p = head;
  50. while (p != null) {
  51. counter++;
  52. p = p.next;
  53. }
  54. return counter;
  55. }
  56. //选择排序
  57. public ListNode sort() {
  58. ListNode p = head;
  59. ListNode q;
  60. while (p.next != null) {
  61. q = p.next;
  62. while (q != null) {
  63. if (p.val < q.val) {
  64. int temp = p.val;
  65. p.val = q.val;
  66. q.val = temp;
  67. }
  68. q = q.next;
  69. }
  70. p = p.next;
  71. }
  72. return head;
  73. }
  74. public void print() {
  75. ListNode p = head;
  76. while (p != null) {
  77. System.out.print(p.val + " ");
  78. p = p.next;
  79. }
  80. }
  81. }
  82. public class Test {
  83. public static void main(String[] args) {
  84. MyLinkedList list = new MyLinkedList();
  85. for (int i = 0; i < 10; i++) {
  86. list.add(new ListNode(i));
  87. }
  88. list.print();
  89. System.out.println();
  90. System.out.println("链表长度:" + list.length());
  91. if (list.delete(2)) {
  92. System.out.println("删除成功");
  93. }
  94. list.print();
  95. System.out.println();
  96. System.out.println("链表长度:" + list.length());
  97. list.sort();
  98. list.print();
  99. System.out.println();
  100. System.out.println("链表长度:" + list.length());
  101. }
  102. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注