反转链表

  • 对于反转链表的思想感觉很别扭,需要多看,多想,克服困难
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode resultNode = null;
        ListNode ahead = head;
        ListNode before = null;
        if(ahead == null || ahead.next ==null)
            return ahead;;
        while(ahead !=null){
            ListNode nextNode = ahead.next;
            if(nextNode==null)
                resultNode = ahead;
            
            ahead.next = before;
            before = ahead;
            ahead = nextNode;
        }
        return resultNode;
    }
}

程序需要的变量:
1) 结果链表resultNode =null
2) 新的头结点ahead = head
3) 新的尾节点before = null

过程:
1、首先边界判断,如果只有一个节点或者没有节点,直接输出为原始链表ahead = head;
2、使用循环方式,依次的将原始链表节点进行翻转

全部评论

相关推荐

神哥了不得:(非引流)先把你的个人信息打码一下吧,看了几万份的简历,让我不知道该怎么说
点赞 评论 收藏
分享
03-02 10:51
邵阳学院 Java
红鲤鱼与绿鲤鱼i:看了你的头像不像找工作,像在找妹子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务