算法----翻转单链表

遍历反转发:遍历翻转法是从前往后翻转各个结点的指针域的指向。
基本思路:将当前结点current的下一个结点current.next缓存到temp后如(1->2->3->4,当前结点是1,当前结点的下一个结点2缓存到temp中),然后更改当前结点指向上一个结点newhead(1指向null),也就是说在翻转当前结点的指针指向前,先把当前结点的指针域用temp临时保存。然后先前结点等于当前结点。当前结点等于最开始保存的temp。

反复思考:链表跟我们认识的数组不一样,我们拿到链表的方式是只能拿到头结点,然后不断判断结点中的下一个结点是否为空,从而达到遍历链表的目的
翻转链表一样,我们能拿到的只有头结点。首先我们要定义两个结点一个是newhead一个是temp
newhead用来当最新的头结点,而temp则保存当前结点的下一个结点,也就是说在翻转当前结点的指针指向前,先把当前结点的指针域用temp临时保存,否则断开当前结点指向下一个结点的时候,后面的连接就会丢失
所以首先定义函数

public Node reverse(Node node){}

然后进行判断,如果没有元素或者元素的下一个结点为空,那么不用翻转直接返回

if(node == null){
	return null;		
}
if(node.next == null){
	return node;
}

接下来定义两个结点

Node newhead = null;
Node current = node;

然后进入while循环,只到当前结点不为空

while(current != null){
	//temp则保存当前结点的下一个结点
	Node temp = current.next;
	//保存之后当前结点再指向新结点,指向newhead,第一次循环newhead为空
	current.next = newhead;
	//newhead指向当前结点
	newhead = current;
	//当前结点指向保存的当前切点的next结点
	current = temp;
}

整个下来就是

public Node reverse(Node node){
		if (node == null) {
			return null;
		}
		if (node.next == null) {
			return node;
		}
		Node newhead = null;
		Node current = node;
		while (current != null) {
			Node temp = current.next;
			current.next = newhead;
			newhead = current;
			current = temp;
		}
		return newhead;
	}

接下来就是比较头疼的就是每K个结点反转链表的问题了
1.每K个结点反转链表,最后不足K个的也反转

public static Node ReverseList(Node head, int K){
		if (head == null) {
			return head;
		}
		if (head.next == null) {
			return head;
		}
		Node current = head;
		Node newhead = null;//到这里跟之前反转链表一样
		int count = 0;
		while (count < K && current != null) {//前面只是加了一个count<K的判断
			Node temp = current.next;
			current.next = newhead;
			newhead = current;
			current = temp;//一样
			
			count++;
		}
		if (current != null) {
			head.next = ReverseList(current, K);
		}
		return newhead;
	}

2.每K个结点反转链表,不足K个是不反转

	// 扩展 每K个结点一组反转链表,最后不足K个不反转
	public static Node ReverseList2(Node head, int K) {
		if (head == null || head.next == null) {
			return head;
		}
		Node current = head;
		Node newhead = null;
		int count = 0;
		if (getLength(current) >= K) {
			while (count < K && current != null) {// 前面只是加了一个count<K的判断》
				Node temp = current.next;
				current.next = newhead;
				newhead = current;
				current = temp;// 一样

				count++;
			}
			if (current != null) {
				head.next = ReverseList(current, K);
			}
			return newhead;
		}
		return current;
	}

	public static int getLength(Node head) {
		Node node = head;
		int count = 0;
		while (node != null) {
			count++;
			node = node.next;
		}
		return count;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值