前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >反转链表,不能用辅助数据结构

反转链表,不能用辅助数据结构

作者头像
酒楼
发布2024-01-08 08:57:48
960
发布2024-01-08 08:57:48
举报
文章被收录于专栏:酒楼酒楼

反转链表

1.不能用辅助数据结构,不能用递归,链表自己定义 next int

代码语言:javascript
复制
//单向链表节点
public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

/**
* 反转链表的方法
* @param head 链表的头节点
* @return ListNode 一个反转后的头结点
*/
public ListNode reverseList(ListNode head) {
    ListNode cur = head;
    ListNode pre = null;
    while(cur!=null){
    	//保存当前节点下一个节点
        ListNode temp = cur.next;
        //指向前一个节点(头结点指向null)
        cur.next = pre;
        pre = cur;
        cur = temp;
    }
    //将反转后的链表头节点返回
    return pre;
}

2.我写的垃圾代码

代码语言:javascript
复制
//类似冒泡,将第一个val一直冒泡到最后一位,以此类推
private static ListNode turnList(ListNode input) {
	if(input == null) {
		return null;
	}
	ListNode node = input;
	ListNode now = input;
	
	//获取链表长度
	int length =0;

	while(node!=null) {
		length++;
		node = node.next;
	}

	
	for(int i = 0;i<length;i++) {
		node = input;
		System.out.println("exchange time:"+(length-i));
		//int val = node.value;
		//这个地方用到了i,用i来控制要交换多少次,第一个要交换length-1次,第二个要交换length-2,第n个交换length-n
		for(int j = 0;j<length-i-1;j++) {
			
			if(node.next == null) {
				break;
			}
			exchange(node,node.next);
			PrintList(input);
			node = node.next;
		}
		now = now.next;
	}

	return input;
}

private static void exchange(ListNode node, ListNode next) {
	int val = node.value;
	node.value = next.value;
	next.value = val;		
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-01-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 反转链表
    • 1.不能用辅助数据结构,不能用递归,链表自己定义 next int
      • 2.我写的垃圾代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档