码迷,mamicode.com
首页 > 编程语言 > 详细

从单链表中删除最大的元素,单链表元素排序

时间:2015-06-09 17:10:25      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

public class LinkList {

	public Node head;
	public LinkList() {
		head = new Node();
		head.next = null;
	}
	
	//尾插法
	public void createByTail(int[] arr, int n) {
		Node tail = head;
		for(int i=0; i<n; i++) {
			Node c = new Node(arr[i]);
			tail.next = c;
			tail = c;
		}
		tail.next = null;
	}
	
	//头插法
	public void createByHead(int[] arr, int n) {
		head.next = null;
		for(int i=0; i<n; i++) {
			Node c = new Node(arr[i]);
			c.next = head.next;
			head.next = c;
		}
	}
	
	public void display() {
		Node p = head.next;
		while(p != null) {
			if(p.next != null)
				System.out.print(p.data + "->");
			else 
				System.out.println(p.data);
			p = p.next;
		}
	}
	
	//删除单链表中元素最大的节点
	public void delMaxNode() {
		Node p = head.next, pre = head, maxp = head.next, maxpre = head;
		while(p != null) {
			if(p.data > maxp.data) {
				maxp = p;
				maxpre = pre;
			}
			pre = p;
			p = p.next;
		}
		maxpre.next = maxp.next;
        display();
	}
	
	//单链表元素排序
	public void sort() {
		Node p = head.next.next;
		head.next.next = null;
		Node q, pre;
		while(p != null) {
			q = p.next;
			pre = head;
			while(pre.next != null && pre.next.data < p.data) {
				pre = pre.next;
			}
			p.next = pre.next;
			pre.next = p;
			p = q;
		}
		display();
	}
	
	public static void main(String[] args) {
		int[] arr = new int[]{5,6,1,6,9,3,7,8};
		LinkList list = new LinkList();
		list.createByHead(arr, arr.length);
		list.display();
		list.createByTail(arr, arr.length);
		list.display();
		list.delMaxNode();
		list.sort();
		
		
		
	}

}
class Node {
	public int data;
	public Node next;
	public Node(){}
	public Node(int data) {
		this.data = data;
	}
}


结果:


8->7->3->9->6->1->6->5
5->6->1->6->9->3->7->8
5->6->1->6->3->7->8
1->3->5->6->6->7->8


从单链表中删除最大的元素,单链表元素排序

标签:

原文地址:http://blog.csdn.net/qhairen/article/details/46428879

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!